Adam Matan
Adam Matan

Reputation: 136381

JQuery JSON-within-JSON parsing

Consider the following nested JSON:

{
  "state": [
    "Tennessee"
  ], 
  "more_data": [
    {
      "letters": {
        "last": "e", 
        "first": "T"
      }
    }
  ]
}

I want to print the JSON in JavaScript in a flat manner, i.e. root_key=value:

  var my_json_str = "{\"state\":[\"Tennessee\"],\"more_data\":[{\"letters\":{\"first\":\"T\",\"last\":\"e\"}}]}";
  console.log(my_json_str);
  my_json = jQuery.parseJSON(my_json_str);
  for (var key in my_json) {
      console.log(key,":",my_json[key]);
  }

But I get (FireBug console):

state : ["Tennessee"]
more_data : [Object { letters={...}}]

Instead of the desired:

state:["Tennessee"]
more_data:[{"letters":{"first":"T","last":"e"}}]

How do I fix this?

Solution - following your answers:

http://jsfiddle.net/wrAUB/

var jsonStr = "{\"state\":[\"Tennessee\"],\"more_data\":[{\"letters\":{\"first\":\"T\",\"last\":\"e\"}}]}";

var jsonObj = JSON.parse(jsonStr);
for (key in jsonObj) {
    console.log(key+':'+JSON.stringify(jsonObj[key]));
}
​

Which gives:

state:"Tennessee"
more_data:{"letters":{"first":"T","last":"e"}}

Upvotes: 4

Views: 9093

Answers (2)

millimoose
millimoose

Reputation: 39980

You can use JSON.stringify to turn the objects you're iterating over back into JSON strings:

var jsonStr = "{\"state\":[\"Tennessee\"],\"more_data\":[{\"letters\":{\"first\":\"T\",\"last\":\"e\"}}]}";

​var jsonObj = JSON.parse(jsonStr);
for (key in jsonObj) {
    console.log(key+':'+JSON.stringify(jsonObj[key]));
}

See it in action on jsFiddle: http://jsfiddle.net/hEvFr/

Upvotes: 5

smcg
smcg

Reputation: 3273

Sounds like you would want to call JSON.stringify on the values of the key-value pairs.

Upvotes: 2

Related Questions