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;
};
Well, the problem is that you're creating AN ARRAY then continue working with it as with an object.
Use
user.regions[a] = {};
instead.
What happens is that JSON.stringify sees there is an array, tries to iterate over its numeric indexes which it does not have so it results in an empty array.
Example on JSFiddle: http://jsfiddle.net/Le80jdsj/
I came here with the same issue of seemingly losing data with JSON.stringify. Although when I would console.Log() I'd see the data existing.
PSA Let's just all agree to remember to make sure synchronous logic isn't in async functions ๐คฆโโ๏ธ
How can I remove escape sequences from JSON.stringify so that it's human-readable?
How to remove nested JSON.stringify() properties
How to remove special characters from json.stringify
How to remove \n after JSON.stringfy?
You can use the replacer. The second parameter provided by JSON.stringify.Replacer could be a function or array.
In your case we can create a function which replaces all the special characters with a blank space.The below example replaces the whitespaces and underscores.
function replacer(key, value) {
return value.replace(/[^\w\s]/gi, '');
}
var foo = {"a":"1","b":2};
var jsonString = JSON.stringify(foo, replacer);
If you simply want to replace the one special character, use:
JSON.stringify({ a: 1, b: 2 }, null, '\t');
For more information on replacer, check the MDN page JSON.stringify().
ECMAScript 2021, the 12th edition
You can use
JSON.stringify() and replaceAll()
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
const foo = {
A: 'This is my \\',
B: 'This \\ is his \\'
};
let jsonString = JSON.stringify(foo, null, 2);
document.write(jsonString);
jsonString = jsonString.replaceAll('\\', '');
document.write('<pre>' + jsonString + '</pre>');
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);
How to remove special characters from json.stringify EMAIL IS: "{\"email\":\"harrypotter2@gmail.com\"}" and also that email . I just want harrypotter2@gmail.com
In your data screenshots, you literally see "\n".
This probably means that the actual string doesn't contain a newline character (\n), but a escaped newline character (\\n).
A newline character would have been rendered as a linebreak. You wouldn't see the \n.
To remove those, use .replace(/\\n/g, '') instead of .replace(/\n/g, '')
just :=>
JSON.stringify(JSON.parse(<json object>))
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.