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.

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

6 Comments

Hi Oleg, when i am passing my obj to this function it is not printing anything.
no it is still not working. My code is in angular 7.I am calling this function from same class.
I add snippet, so you can run it . Also I puit else for showing only flat node
"ERROR ReferenceError: checkNested is not defined", this error is coming
It is running now but problem is still not resolved, I need keys also
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.