The Mozilla docs say to return undefined (instead of "none"):
http://jsfiddle.net/userdude/rZ5Px/
function replacer(key,value)
{
if (key=="privateProperty1") return undefined;
else if (key=="privateProperty2") return undefined;
else return value;
}
var x = {
x:0,
y:0,
divID:"xyz",
privateProperty1: 'foo',
privateProperty2: 'bar'
};
alert(JSON.stringify(x, replacer));
Here is a duplication method, in case you decide to go that route (as per your comment).
http://jsfiddle.net/userdude/644sJ/
function omitKeys(obj, keys)
{
var dup = {};
for (var key in obj) {
if (keys.indexOf(key) == -1) {
dup[key] = obj[key];
}
}
return dup;
}
var x = {
x:0,
y:0,
divID:"xyz",
privateProperty1: 'foo',
privateProperty2: 'bar'
};
alert(JSON.stringify(omitKeys(x, ['privateProperty1','privateProperty2'])));
EDIT - I changed the function key in the bottom function to keep it from being confusing.
Answer from Jared Farrish on Stack OverflowThe Mozilla docs say to return undefined (instead of "none"):
http://jsfiddle.net/userdude/rZ5Px/
function replacer(key,value)
{
if (key=="privateProperty1") return undefined;
else if (key=="privateProperty2") return undefined;
else return value;
}
var x = {
x:0,
y:0,
divID:"xyz",
privateProperty1: 'foo',
privateProperty2: 'bar'
};
alert(JSON.stringify(x, replacer));
Here is a duplication method, in case you decide to go that route (as per your comment).
http://jsfiddle.net/userdude/644sJ/
function omitKeys(obj, keys)
{
var dup = {};
for (var key in obj) {
if (keys.indexOf(key) == -1) {
dup[key] = obj[key];
}
}
return dup;
}
var x = {
x:0,
y:0,
divID:"xyz",
privateProperty1: 'foo',
privateProperty2: 'bar'
};
alert(JSON.stringify(omitKeys(x, ['privateProperty1','privateProperty2'])));
EDIT - I changed the function key in the bottom function to keep it from being confusing.
Another good solution: (requires underscore)
x.toJSON = function () {
return _.omit(this, [ "privateProperty1", "privateProperty2" ]);
};
The benefit of this solution is that anyone calling JSON.stringify on x will have correct results - you don't have to alter the JSON.stringify calls individually.
Non-underscore version:
x.toJSON = function () {
var result = {};
for (var x in this) {
if (x !== "privateProperty1" && x !== "privateProperty2") {
result[x] = this[x];
}
}
return result;
};
how to remove json object key and value.? - javascript
Typescript JSON.stringify, remove key property name
How to remove nested JSON.stringify() properties
how to remove json object key and value.?
delete operator is used to remove an object property.
delete operator does not returns the new object, only returns a boolean: true or false.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean
value.
How to remove Json object specific key and its value ?
You just need to know the property name in order to delete it from the object's properties.
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.
let value="test";
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(myjsonobj);
There are several ways to do this, lets see them one by one:
- delete method: The most common way
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
delete myObject['currentIndustry'];
// OR delete myObject.currentIndustry;
console.log(myObject);
- By making key value undefined: Alternate & a faster way:
let myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
myObject.currentIndustry = undefined;
myObject = JSON.parse(JSON.stringify(myObject));
console.log(myObject);
- With es6 spread Operator:
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
const {currentIndustry, ...filteredObject} = myObject;
console.log(filteredObject);
Or if you can use omit() of underscore js library:
const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);
When to use what??
If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.
hope this helps :)
You can pass a "replacer" function that returns the exact value you want.
var data = {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100};
var result = JSON.stringify(data, function(k, v) {
switch (k) {
case "": case "name": case "resistance":
return v
case "inputPort": case "outputPort":
return v.id
default:
return undefined;
}
}, 2)
document.querySelector("pre").textContent = result
<pre></pre>
The "" represents the top level object. For that, "name", and "resistance", it simply returns the original value.
For "inputPort" and "outputPort" it returns the id property.
Anything else gets undefined, which means it gets omitted from the result.
You can use a replacer function for this.
var obj = {
"id": 1,
"name": "Light Switch",
"lightStatus": true,
"inputPort": {
"id": 2,
"value": 0
},
"outputPort": {
"id": 2,
"value": false
},
"resistance": 100
};
var stringified = JSON.stringify(obj, function(key, val) {
if (key === 'id' || key === 'lightStatus') {
return void(0);
}
if (key === 'inputPort' || key === 'outputPort') {
return val.id;
}
return val;
});
console.log(stringified);
delete operator is used to remove an object property.
delete operator does not returns the new object, only returns a boolean: true or false.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean
value.
How to remove Json object specific key and its value ?
You just need to know the property name in order to delete it from the object's properties.
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.
let value="test";
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(myjsonobj);
There are several ways to do this, lets see them one by one:
- delete method: The most common way
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
delete myObject['currentIndustry'];
// OR delete myObject.currentIndustry;
console.log(myObject);
- By making key value undefined: Alternate & a faster way:
let myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
myObject.currentIndustry = undefined;
myObject = JSON.parse(JSON.stringify(myObject));
console.log(myObject);
- With es6 spread Operator:
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
const {currentIndustry, ...filteredObject} = myObject;
console.log(filteredObject);
Or if you can use omit() of underscore js library:
const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);
When to use what??
If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.
hope this helps :)
JSON.stringify has an often overlooked parameter called the replacer. It can accept an array of key names to include in the json output:
JSON.stringify(data, ["ID","VERSION"], " "); // FILE is excluded
Snippet
Run the snippet to see the output with and without using the replacer.
let data = {
"ID": "2196",
"VERSION": "1-2022",
"FILE": "2196.docx"
};
console.log("Without replacer: ",
JSON.stringify(data, null, " ")
);
console.log("Using replacer: ",
JSON.stringify(data, ["ID","VERSION"], " ")
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You should not stringify the object before removing the key.
function test() {
var json = {
"ID": "2196",
"VERSION": "1-2022",
"FILE": "2196.docx"
};
// stringify to show in console as string
json = JSON.stringify(json)
console.log("json " + json);
// convert back to object so you can remove the key
json = JSON.parse(json);
delete json['FILE'];
// stringify to show new object in console as string
json = JSON.stringify(json);
console.log("json " + json);
return;
}
test();
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Your replacer function is not correct. It needs to return the value whenever you want to include the key/value in the JSON. Your code makes it only return undefined whatever the key/value.
So use this one:
function replacer(key, value) {
if (key !== "preset") { return value; }
}
Or alternatively, you could test for the type of the value:
function replacer(key, value) {
if (!(value instanceof Preset)) { return value; }
}
Delete the key on a copy of the objecrt before stringifying the object to get your result. You can create some sort of function that deletes a key from an object if it exists.
var obj = {
id: '1',
presetKey: 'abc',
preset: 'preset',
}
function filterPreset(obj, key) {
if (typeof obj === 'object' && obj[key]) {
var copy = Object.assign({}, obj);
delete copy[key];
return copy;
}
return obj;
}
console.log('result', JSON.stringify(filterPreset(obj, 'preset')));
console.log('no mutation', obj);
This simple regular expression solution works to unquote JSON property names in most cases:
const object = { name: 'John Smith' };
const json = JSON.stringify(object); // {"name":"John Smith"}
console.log(json);
const unquoted = json.replace(/"([^"]+)":/g, '$1:');
console.log(unquoted); // {name:"John Smith"}
Extreme case:
var json = '{ "name": "J\\":ohn Smith" }'
json.replace(/\\"/g,"\uFFFF"); // U+ FFFF
json = json.replace(/"([^"]+)":/g, '$1:').replace(/\uFFFF/g, '\\\"');
// '{ name: "J\":ohn Smith" }'
Special thanks to Rob W for fixing it.
Limitations
In normal cases the aforementioned regexp will work, but mathematically it is impossible to describe the JSON format with a regular expression such that it will work in every single cases (counting the same number of curly brackets is impossible with regexp.) Therefore, I have create a new function to remove quotes by formally parsing the JSON string via native function and reserialize it:
function stringify(obj_from_json) {
if (typeof obj_from_json !== "object" || Array.isArray(obj_from_json)){
// not an object, stringify using native function
return JSON.stringify(obj_from_json);
}
// Implements recursive object serialization according to JSON spec
// but without quotes around the keys.
let props = Object
.keys(obj_from_json)
.map(key => `${key}:${stringify(obj_from_json[key])}`)
.join(",");
return `{${props}}`;
}
Example: https://jsfiddle.net/DerekL/mssybp3k/
It looks like this is a simple Object toString method that you are looking for.
In Node.js this is solved by using the util object and calling util.inspect(yourObject). This will give you all that you want. follow this link for more options including depth of the application of method. http://nodejs.org/api/util.html#util_util_inspect_object_options
So, what you are looking for is basically an object inspector not a JSON converter. JSON format specifies that all properties must be enclosed in double quotes. Hence there will not be JSON converters to do what you want as that is simply not a JSON format.Specs here: https://developer.mozilla.org/en-US/docs/Using_native_JSON
Object to string or inspection is what you need depending on the language of your server.
It sounds like you are looking for a data-serialization format that is human-readable and version-control-friendly but not as strict about quotes as JSON.
Such formats include:
- Relaxed JSON (RJSON) (simple keys and simple values generally do not require quotes)
- Hjson (simple keys and simple values generally do not require quotes)
- YAML (keys and values generally do not require quotes)
- JavaScript object literal (also printed out by many implementations of "console.dir()" when passed a JavaScript object; simple keys generally not required to be quoted, but string values must be quoted by either single quotes or double quotes)
for completeness:
JSON (requires double-quotes around keys, also called property names, and requires double-quotes around string data values).
Yes, it is possible to remove the quotes from the keys. Doing so will render it invalid as JSON, but still valid when used directly in JavaScript code, only if the keys you use are also valid variable names. When you paste a JSON object in JavaScript code, it may be useful to have the quotes removed, as they can in some cases take up a lot of data. If that's relevant to your project, then this is the answer for you.
The function below works for any JavaScript variable and works fine with objects/arrays containing objects/arrays. I've added comments to explain what's going on. Please note that this code does not check for possible reserved keywords that may not be allowed as JavaScript keys, such as "for".
function toUnquotedJSON(param){ // Implemented by Frostbolt Games 2022
if(Array.isArray(param)){ // In case of an array, recursively call our function on each element.
let results = [];
for(let elem of param){
results.push(toUnquotedJSON(elem));
}
return "[" + results.join(",") + "]";
}
else if(typeof param === "object"){ // In case of an object, loop over its keys and only add quotes around keys that aren't valid JavaScript variable names. Recursively call our function on each value.
let props = Object
.keys(param)
.map(function(key){
// A valid JavaScript variable name starts with a dollar sign (?), underscore (_) or letter (a-zA-Z), followed by zero or more dollar signs, underscores or alphanumeric (a-zA-Z\d) characters.
if(key.match(/^[a-zA-Z_$][a-zA-Z\d_$]*$/) === null) // If the key isn't a valid JavaScript variable name, we need to add quotes.
return `"${key}":${toUnquotedJSON(param[key])}`;
else
return `${key}:${toUnquotedJSON(param[key])}`;
})
.join(",");
return `{${props}}`;
}
else{ // For every other value, simply use the native JSON.stringify() function.
return JSON.stringify(param);
}
}