-4

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 ?

Gissipi_453
  • 1,250
  • 1
  • 25
  • 61
  • 4
    Do me a favor, google your exact title, and read up a little bit. You'll find answers on this from research faster than waiting here for an answer. – Sterling Archer Aug 29 '16 at 16:17
  • Your code will throw an error. You must use template literals to include new lines. To parse string, use `JSON.parse` function. –  Aug 29 '16 at 16:17
  • 3
    `JSON.parse()` And technically speaking, why would you write code like this? JSON is already valid javascript. all you'd need was `var foo = {"Name": .... };` and you wouldn't need to parse anything. the JS parser would already have done that for you. – Marc B Aug 29 '16 at 16:17

1 Answers1

1

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/

Rafi Ud Daula Refat
  • 2,187
  • 19
  • 28