0

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

5
  • 2
    $.each(data.one[0]) Commented Apr 19, 2022 at 18:19
  • 1
    based on your data "one" and "two" each contain a single dimension array. So you are either not going deep enough to obtain the other objects or maybe you didn't mean to use those square brackets. Commented Apr 19, 2022 at 18:22
  • @Aioros solution works, Thanks. Commented Apr 19, 2022 at 18:25
  • @Fnostro, it does need to be an array right? if I lose the square brackets, and drop [0] from the date.one, it doesn't work.. Commented Apr 19, 2022 at 18:29
  • 1
    see snippet in my anwer. Commented Apr 19, 2022 at 18:47

2 Answers 2

1

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);

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

2 Comments

You were correct. I must have done something wrong. My name is clueless for a reason. I will accept your answer, thank you for expanding.
Glad to help. We were all clueless once :) Happy coding.
1

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:{}

1 Comment

Thank you. The other answer was more direct to what I was wondering about. Though this is more verbose, and I may use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.