0

I have an object

{
  "p1": "hoho",
  "p2": "haha",
  "p3": {
     "v1": "hehe",
     "v2": "{\"m1\":\"content1\", \"m2\":\"content2\"}"
  }
}

How to convert it into:

{
  "p1": "hoho",
  "p2": "haha",
  "p3": {
     "v1": "hehe",
     "v2": {
        "m1":"content1", 
        "m2":"content2"
     }
  }
}

The question is most for converting nested JSON string inner Object to JSON.

Blue
  • 22,608
  • 7
  • 62
  • 92
sower
  • 71
  • 1
  • 5
  • Possible duplicate of [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Tareq Aug 02 '18 at 23:22
  • 1
    @Tareq Not even remotely close. – Blue Aug 02 '18 at 23:24

2 Answers2

1

You can write a simple recursive function to attempt to expand the object (If it's JSON):

var data = {
  "p1": "hoho",
  "p2": "haha",
  "p3": {
     "v1": "hehe",
     "v2": "{\"m1\":\"content1\", \"m2\":\"content2\"}"
  }
}

function jsonExpand(obj) {
  for (var k in obj) {
    if (!obj.hasOwnProperty(k))
      continue;       // skip this property
      
    if (typeof obj[k] == "object" && obj[k] !== null) {
      jsonExpand(obj[k]);
    } else {
      try {
        obj[k] = JSON.parse(obj[k]);
      } catch (e) {
        // Not able to be parsed
      }
    }
  }
}

jsonExpand(data);

console.log(data);
Blue
  • 22,608
  • 7
  • 62
  • 92
  • Thank you so much. But instead of modifying the object itself, how to return a copy of the object? if obj is null, I would like to return 'undefined' – sower Aug 02 '18 at 23:46
  • @sower You have the recursive function. Feel free to modify it as needed. – Blue Aug 02 '18 at 23:48
0

Alternative can be to parse it during parsing:

j = JSON.stringify({"p1":"hoho","p2":"haha","p3":{"v1":"hehe","v2":"{\"m1\":\"content1\", \"m2\":\"content2\"}"}})

o = JSON.parse(j, (k, v) => v === null ? undefined : v[0] == '{' ? JSON.parse(v) : v);

console.log( o );
Slai
  • 22,144
  • 5
  • 45
  • 53