Might be a duplicate question, but couldn't find the answer. I want to stringify a javascript object that contains some JSON strings as values.
For example:
var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};
As you see, the value for key 'options' is a JSON string. I want to stringify the object 'obj', without double stringifying the inner JSON string.
Is there any clean and neat solution for this, except parsing each value with JSON string and stringifying the object?
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
stringify() JSON stringification is the process of converting a Javascript object to a flat JSON string that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. stringify() , as the Javascript standard specifies.
Simply use JSON stringify() method to JSON stringify the array of objects in JavaScript.
JSON. stringify() takes a JavaScript object and then transforms it into a JSON string. JSON. parse() takes a JSON string and then transforms it into a JavaScript object.
Assuming you don't know which properties are JSON, you could use the replacer function parameter on JSON.stringify to check if a value is a JSON string. The below example tries to parse each string inside a try..catch , so is not the most efficient, but should do the trick (on nested properties as well)
var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};
function checkVal(key,val){
if(typeof val === 'string'){
try{return JSON.parse(val);}catch(e){}
}
return val;
}
var res = JSON.stringify(obj,checkVal);
console.log('normal output', JSON.stringify(obj))
console.log('with replacer', res);
No, you can't do that.
If you did not encode that string, JSON.parse will not return a correct string.
The cleanest solution to do that is use JSON for obj.options, and stringify it when you need to use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With