Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON Object that contains Json string

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"
      }
}
like image 636
nadhem Avatar asked Aug 09 '17 23:08

nadhem


People also ask

How do you parse a string of JSON response?

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.

Can we JSON parse a string?

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.

Can you parse a JSON object?

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.

How do I convert a JSON object to a string?

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.


1 Answers

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?

like image 55
A. Vidor Avatar answered Oct 23 '22 06:10

A. Vidor