最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to fetch value from keys in JSON object? - Stack Overflow

programmeradmin2浏览0评论

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

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
Share Improve this question edited Apr 10, 2013 at 14:41 Default 16.5k3 gold badges28 silver badges38 bronze badges asked Apr 10, 2013 at 14:31 SoumyaSoumya 8933 gold badges17 silver badges33 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Just use for..in to loop an object:

for (var key in jsonObj) {
  document.write(key);  
  document.write(jsonObj[key]);  
}

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.

Your "doesn't work" line should be:

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

You're bining 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]]);
发布评论

评论列表(0)

  1. 暂无评论