admin管理员组

文章数量:1297076

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"
      }
}

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"
      }
}
Share Improve this question edited Dec 29, 2020 at 20:18 nadhem asked Aug 9, 2017 at 23:45 nadhemnadhem 1881 gold badge5 silver badges22 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 1

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?

We'll write a handy little utility which maps a function over object properties:

function mapObject(obj, fn) {
  const result = {};
  for (const prop in obj) result[prop] = fn(obj[prop], prop);
  return result;
}

Now you can create an object with all the JSON values in the input parsed by just saying

mapObject(obj, JSON.parse)

If you want to guard against property values which are not valid JSON, then

function parseJSON(x) {
  try { return JSON.parse(x); }
  catch (e) { return x; }
}

and then

mapObject(obj, parseJSON)

You could use Object.keys(obj) to get the property names to allow you to use JSON.parse()

You can always try/pass on every key:

a = {
  a: 1,
  b: JSON.stringify({a: 1, b: 2}),
  c: 'asdf'
}
console.log(a);
new_a = {}
Object.keys(a).map((key) => {
  try {
    new_a[key] = JSON.parse(a[key]);
  } catch(err) {
    new_a[key] = a[key];
  }
})

console.log(new_a);

You can simply loop over all the keys:

obj={
  Name: "{\"FisrtName\":\"Douglas\",\"LastName\":\"Crockford\"}",
  Other: "This isn't JSON"
};
for (var key in obj) {
    try {
        obj[key] = JSON.parse(obj[key]);
    } catch(err) {
        // ignore error, just leave it alone
    }
}
console.log(obj);

I have succeeded with : jsonData['key']['value']

本文标签: javascriptParse JSON Object that contains Json stringStack Overflow