Clueless
Clueless

Reputation: 57

Get nested JSON keys only

Example JSON

{
  "one": [{
    "A": {"name":"example"},
    "B": {}
  }],
  "two": [{
    "A": {"name":"booger"},
    "B": {}
  }]
}

Using this I can get keys "one" and "two" to be listed.

$.getJSON('blahblah.js', function(data){
  $.each(data, function(key){
    console.log(key);
  });
});

But using this, I can't get "A" and "B" to be listed.

$.getJSON('blahblah.js', function(data){
  $.each(data.one, function(key){
    console.log(key);
  });
});

Why not? And how do I get those inner keys(is this the correct term?) to be listed. Thanks

Upvotes: 0

Views: 230

Answers (2)

fnostro
fnostro

Reputation: 4591

So...not sure what you're seeing then...

var jsontext_withbrackets =
  '{"one":[{"A":{"name": "example"},"B":{}}],\
  "two":[{"A":{"name": "booger" },"B":{}}]}';

var obj1 = JSON.parse(jsontext_withbrackets);

var jsontext_withoutbrackets =
  '{"one":{"A":{"name": "example"},"B":{}},\
  "two":{"A":{"name": "booger" },"B":{}} }';

var obj2 = JSON.parse(jsontext_withoutbrackets);

console.log(obj1.one[0]);
console.log(obj2.one);

Upvotes: 1

Serge
Serge

Reputation: 43959

try this

$.each(data, function (key) {
  data[key].forEach((element) => {
    $.each(element, function (item) {
      console.log(key + ":"+item + ":" + JSON.stringify(element[item]));
    });
  });
});

result

one:A:{"name":"example"}
one:B:{}
two:A:{"name":"booger"}
two:B:{}

Upvotes: 1

Related Questions