简体   繁体   English

键为变量时未获取JSON值

[英]Not getting JSON value when key is a variable

i have come across a peculiar problem. 我遇到了一个特殊的问题。 That is i can able to access the value of a JSON array when i am doing it directly with key. 那就是当我直接用key进行操作时,我能够访问JSON数组的值。 But it is not getting the same when key is a variable. 但是当key是一个变量时,它并不会得到相同的结果。 For eg., 例如

var response = {"jpg":{"table_name":"tbl_photo"}};

alert(response.jpg.table_name);
var fileType = "jpg";
alert(response.fileType.table_name);

In this, the first alert is getting triggered correctly. 这样,第一个警报将被正确触发。 But in the second, where we are passing the key as a variable, it is not working. 但是在第二个中,我们将键作为变量传递,但它不起作用。

Here is the fiddle link of this, http://jsfiddle.net/aAZeT/ 这是此链接的小提琴, http://jsfiddle.net/aAZeT/

Can anybody help me in this? 有人可以帮我吗?

For strings you need index operation ie [] : 对于字符串,您需要索引操作,即[]:

var response = {"jpg":{"table_name":"tbl_photo"}};

alert(response.jpg.table_name);
var fileType = "jpg";
alert(response[fileType].table_name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM