Javascript如何解析JSON数组

我正在使用Sencha Touch(ExtJS)从服务器获取JSON消息。我收到的消息是这个:

{

"success": true,

"counters": [

{

"counter_name": "dsd",

"counter_type": "sds",

"counter_unit": "sds"

},

{

"counter_name": "gdg",

"counter_type": "dfd",

"counter_unit": "ds"

},

{

"counter_name": "sdsData",

"counter_type": "sds",

"counter_unit": " dd "

},

{

"counter_name": "Stoc final",

"counter_type": "number ",

"counter_unit": "litri "

},

{

"counter_name": "Consum GPL",

"counter_type": "number ",

"counter_unit": "litri "

},

{

"counter_name": "sdg",

"counter_type": "dfg",

"counter_unit": "gfgd"

},

{

"counter_name": "dfgd",

"counter_type": "fgf",

"counter_unit": "liggtggggri "

},

{

"counter_name": "fgd",

"counter_type": "dfg",

"counter_unit": "kwfgf "

},

{

"counter_name": "dfg",

"counter_type": "dfg",

"counter_unit": "dg"

},

{

"counter_name": "gd",

"counter_type": "dfg",

"counter_unit": "dfg"

}

]

}

我的问题是我无法解析此JSON对象,因此我可以使用每个计数器对象。

我正在尝试像这样完成:

var jsonData = Ext.util.JSON.decode(myMessage);

for (var counter in jsonData.counters) {

console.log(counter.counter_name);

}

我究竟做错了什么 ?谢谢!

回答:

Javascript具有针对字符串的内置JSON解析,我想这就是您拥有的:

var myObject = JSON.parse("my json string");

在您的示例中使用此代码将是:

var jsonData = JSON.parse(myMessage);

for (var i = 0; i < jsonData.counters.length; i++) {

var counter = jsonData.counters[i];

console.log(counter.counter_name);

}

:for循环的使用中有一个错误(我在初读时就错过了这一点,请记入@Evert)。使用for-

in循环会将var设置为当前循环的属性名称,而不是实际数据。请参阅上面的更新循环以了解正确用法

:该JSON.parse方法在旧的旧浏览器中不起作用-因此,如果您打算通过某种时间弯曲的互联网连接来使您的网站可用,这可能是个问题!

以上是 Javascript如何解析JSON数组 的全部内容, 来源链接: utcz.com/qa/421112.html

回到顶部