1

I want to access data inside json file which contains multiple nested objects and I want to print them dynamically without thinking what is the data inside it. I want to print key values inside dynamically.

my json

 {
  "name" : "abc",
  "tags" : "def",
  "updated-by" : "ijk",
  "property" : {
    "description" : "abcd",
    "type" : "string"
  },
  "sources" : {
    "input" : {
      "type" : "lmn",
      "properties" : {
        "key" : "opq"
      }
    }
  }
}

If my key contains object then it should go inside that object and then prints its values but if it is also another object then it should go inside that object also and then print its key value.It should loop dynamically. Code must be in angular 4 or above.If anyone can help.

Swapnali Pode
  • 15
  • 1
  • 2
  • 5
  • 1
    please show us what you have already tried / searched to accomplish this. – jcuypers Feb 21 '19 at 08:17
  • Possible duplicate of [Iterate through Nested JavaScript Objects](https://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objects) – Tushar Walzade Feb 21 '19 at 08:21
  • Possible duplicate of [How can I pretty-print JSON using JavaScript?](https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript) – Andrew Radulescu Feb 21 '19 at 08:23
  • I tried to follow this one https://stackoverflow.com/questions/54760044/how-to-fetch-value-from-json-object-in-angular-6/ but it is only giving me key values for first object but it is not working for nested objects – Swapnali Pode Feb 21 '19 at 08:39

2 Answers2

1

The behavior you are looking for is already covered by JSON.stringify(jsonObject) method.

You can also control the spacing and pretty print the JSON.

Andrew Radulescu
  • 1,862
  • 13
  • 21
0

You can use recursive function.


const myObj = {
  "name" : "abc",
  "tags" : "def",
  "updated-by" : "ijk",
  "property" : {
    "description" : "abcd",
    "type" : "string"
  },
  "sources" : {
    "input" : {
      "type" : "lmn",
      "properties" : {
        "key" : "opq"
      }
    }
  }
}

function checkNested(obj) {
    for (let prop in obj) {        
        if (obj.hasOwnProperty(prop)) {
            if (typeof obj[prop] == "object"){
                console.log(`Key: ${prop}`)
                checkNested(obj[prop]);
            } else {
              console.log(`Key: ${prop} 'value: ${obj[prop]}`)
            }
        }
    }
}


checkNested(myObj)
Oleg
  • 391
  • 3
  • 11