简体   繁体   中英

How to parse all JSON strings in a JavaScript object

I have 1 JavaScript object like this:

result = {
  "status": "success",
  "message": "Get successful!",
  "data": {
      "name":"Hello world",
      "school": {
          "name":"LHP",
          "address":"HCM"
      },
      "class": "[{\"text\":\"Math\",\"code\":\"math124\"},{\"text\":\"Libra\",\"code\":\"libra124\"}]",
      "student": "{\"time_range\":{\"type\":\"select\",\"text\":\"Today\",\"value\":[{\"code\":\"in_today\",\"text\":\"In Today\"}]}}"
  }
}

So I have to parse class and student separately:

result.data.class = JSON.parse(result.data.class);
result.data.student = JSON.parse(result.data.student);

Is there other way to parse the whole result variable or make this step shorter/better?

Thanks

You could loop through the data property's children and parse them.

for (var i = 0; i < Object.keys(result.data).length; i++) {
    try {
        result.data[Object.keys(result.data)[i]] = JSON.parse(result.data[Object.keys(result.data)[i]]);
    } catch (error) {} // it's already JSON
}

But I'd only do that if you're sure you'll only ever have to deal with stringified JSON in the data property of your object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM