Gissipi_453 Gissipi_453 - 3 months ago 9
Javascript Question

Parsing JSON as String in Javascript

I have a String whose value is a JSON object.

var json = '{
"Name": {
"1": "Adam",
"2": "Tim",
"3": "Bob"
},
"Height": {
"1": "181",
"2": "157",
"3": "173"
}
}';


How to parse it to get values Adam, Tim and Bob and print it ?

Answer

As json is a string you need to parse it to make a json object and then you can loop around the object to get your desired value. You can do like following

var json = '{"Name": {"1": "Adam","2": "Tim","3": "Bob"},"Height": {"1": "181","2": "157","3": "173"}}';

var input = JSON.parse(json);

for(var key in input) {
 if(input.hasOwnProperty(key)) {
   if(key === 'Name') {
     for(var innerKey in input[key]) {
       if(input[key].hasOwnProperty(innerKey)) {
          console.log(input[key][innerKey]);
       }
     }
   }
 }
}

Here is the fiddle https://jsfiddle.net/Refatrafi/2q67yezc/2/