I want to parse a JSON Object that contains some value as a json string, note that I don't know those fields previously, so I can't do something like
obj[key]=JSON.parse(obj[key])
. I am looking for an easy way to do that,
obj={
Name:"{\"FirstName\":\"Douglas\",\"LastName\":\"Crockford\"}"
}
And I want to get
{
Name:{
FirstName:"Douglas",
LastName:"Crockford"
}
}
Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
If you want to get paradoxical about it, you can handle arbitrarily nested versions of this scenario using the "reviver parameter". Start by stringifying
your object!
function parseJSON(k,v) {
try { return JSON.parse(v, parseJSON); }
catch(e) { return v; }
}
JSON.parse(JSON.stringify(obj), parseJSON);
Is that nifty, or is it just me?
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