Reputation: 893
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
Upvotes: 2
Views: 4859
Reputation: 160833
Just use for..in
to loop an object:
for (var key in jsonObj) {
document.write(key);
document.write(jsonObj[key]);
}
Upvotes: 3
Reputation: 38345
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]]);
Upvotes: 1
Reputation: 16488
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.
Upvotes: 2
Reputation: 360662
Your "doesn't work" line should be:
document.write(jsonObj[keys[i]]);
^--- no "."
Upvotes: 1