Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting values from json in JavaScript

If I have some json like this:

{
    "dcf93893d83e4f28953f140b9cba1963":{
       "foo":{
          "client":"127.0.0.1",
          "id":"31971",
          "start time":1654131724.160335
       },
       "bar":{
          "client":"127.0.0.1",
          "id":"23456",
          "start time":1654131900.997766
       }
    }
 }

I figured out how to loop through it like this:

for (var key in json) {
    if (json.hasOwnProperty(key)) {
        console.log(json[key])
    }
}

How can I loop through each sub element (foo and bar in this case) and then fetch a key, for example id?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

client, id and start time are the only known key names

Expected output:

31971
23456

EDIT: The json comes from fetch:

setInterval(function () {
    fetch(<url>)
        .then(function (response) {
            return response.json();
        })
        .then(function (json) {
            for (var key in json) {
                if (json.hasOwnProperty(key)) {
                    console.log(json[key])
                }
            }
        })
}, 2000);

>Solution :

Do another loop and grab the inner values by key name:

const json = {
    "dcf93893d83e4f28953f140b9cba1963":{
       "foo":{
          "client":"127.0.0.1",
          "id":"31971",
          "start time":1654131724.160335
       },
       "bar":{
          "client":"127.0.0.1",
          "id":"23456",
          "start time":1654131900.997766
       }
    }
 }
 
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        //console.log(json[key])
        
        for(var key2 in json[key]) {
          console.log(json[key][key2]["id"])
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading