26

我的 JSON 对象计算为:

{ "@io": IO, "@type": XXX }

如果这个变量被调用my_json,我如何访问@typeXXX 的值?我试过my_json.@type了,但这给出了错误。帮助表示赞赏。谢谢,

缺口

4

3 回答 3

43

Use square bracket notation with a string:

var XXXValue = my_json['@type'];

The same can be used when you have a property name in a variable. Using your same example:

var propertyName = '@type';
var XXXValue = my_json[propertyName];
于 2011-08-03T20:21:47.840 回答
10

As you've discovered, you can't use an @ symbol in a Javascript variable name, my_json.@type is invalid.

The good news for you is that you can access your variables as array subscripts. You would do it like this:

my_json["@type"]

Hope that helps.

于 2011-08-03T20:22:59.763 回答
1

If it ends up evaluating you can take the object and probably grab it by the key.

ie obj["@type"]. But something does seem a bit off.

于 2011-08-03T20:22:28.593 回答