2

I want to print all the key value pairs of a JSON object. I don't know the keys of the object, so I am trying to get all the keys and corresponding values in a loop. But it appears that I am missing something obvious.

My perl code

%some_data = ("key1"  => "value1","key2" => "value2","key3"  => "value3","key4" => "value4");
  my $json = encode_json \%some_data;
print $json; # it prints {"key2":"value2","key4":"value4","key1":"value1","key3":"value3"} 

my simple javascript code

var jsonObj=$json;
var keys= Object.keys(jsonObj);
for (var i = 0; i < keys.length; i++){ 
   document.write("<br /> ");
   document.write(keys[i]); 
   // document.write(jsonObj.[keys[i]]);  # doesnt work
}

document.write(jsonObj.key1); #works

4 Answers 4

3

Just use for..in to loop an object:

for (var key in jsonObj) {
  document.write(key);  
  document.write(jsonObj[key]);  
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can't retrieve the value associated with a JavaScript object key by performing jsonObj.[keys[i]]. You should change that line to say jsonObj[keys[i]]. The dot notation will only work for a key that exists in the object. Since [keys[i]] is not actually a property of that object, you cannot use dot notation and must instead use square-bracket notation.

Comments

1

Your "doesn't work" line should be:

document.write(jsonObj[keys[i]]);
                      ^--- no "."

Comments

1

You're combining the square-bracket notation (jsonObj[keys[i]]) and the dot notation (jsonObj.key1) when attempting to call document.write(); they're equivalent to each other so you should only be using one of them. In this case, since the key is dynamic, you should only be using the square bracket notation:

document.write(jsonObj[keys[i]]);

Comments

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.