Key print and json value

I have 2 external json files, and I have to read data from these files using key and value. my application is independent of obj.name object etc. Please help me print these values.

Planets.json

 {
"Planets": [
  { "name": "Mercury",
    "color": "Orange",
    "distance": "57.91 km",
    "radius": "2340 km",
    "year": "0.24085 Earth",
    "day": "88 days",
    "mass": "0.054 Earth"
  },

  { "name": "second",
    "color": "Orange",
    "distance": "57.91 km",
    "radius": "2340 km",
    "year": "0.24085 Earth",
    "day": "88 days",
    "mass": "0.054 Earth"
  }

}

Airports .json

    {
"Airports": [
  {
    "listing": "East 34th Street Heliport",
    "iata": "TSS",
    "type": "Heliport",
    "size": "Tiny"
  }

}

and this is the code I'm trying to do.

              $.ajax({
                url:"planets.json",
                dataType: "json",
                success:function(json){
                    $.each(json, function(key, value){
                        console.log(key + ": " + value);
                    });
                }

            });

and I get it in the console

Planets: [Object Object]

+4
source share
3 answers

Get a nested object using json.Planets[0]and iterate over it.

$.each(json.Planets[0], function(key, value){
    console.log(key + ": " + value);
});

UPDATE 1: If an object contains only one property, you can get it with and do the same as in the previous example. Object.keys()

$.each(json[Object.keys(json)[0]][0], function(key, value){
    console.log(key + ": " + value);
});


2: , $.each() .
$.each(json,function(k, v){
    $.each(v[0], function(key, value){
        console.log(key + ": " + value);
    });
})

3: , Array#forEach, .

json[Object.keys(json)[0]].forEach(function(v){
    $.each(v, function(key, value){
        console.log(key + ": " + value);
    });
});

3: JSON , .

$.each(json,function(k, v){
    v.forEach(function(v1){  
        $.each(v1, function(key, value){
            console.log(key + ": " + value);
        });
    });
})
+4

, ""

$.each(json, function(objectTitle, objects){
    console.log('List of ' + objectTitle + ':');
    $.each(objects, function(objectKey, objectValue){
        console.log(objectKey + ':' +  objectValue);
    });
});
0

To achieve the expected result, use the option below.

$.each(json, function(key, value) {
  $.each(value[0], function(k, val) {
    console.log(k + ":" + val);
  });
});

Codepen- http://codepen.io/nagasai/pen/GqGVGd

0
source

Source: https://habr.com/ru/post/1649456/


All Articles