如何使用JavaScript从JSON对象提取值 [英] How extract value from a json object using javascript

查看:130
本文介绍了如何使用JavaScript从JSON对象提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我使用php脚本生成的json对象

Following is my json object produced using php script

$to_encode[]= mysql_fetch_assoc($result);
echo json_encode($to_encode);

输出为

[{"wid":"2","repid":"1"}]

提取widrepid的值,我在js中给定的代码下面使用了

to extract values of wid and repid I used below given code in js

var obj = JSON.parse(data);

var a = obj.["wid"];
var b = obj.["repid"];

但是我正在将ab的值作为undefined而不是21

but I'm getting value for a and b as undefined instead of 2,1

推荐答案

看起来您的JSON不仅编码了一个对象,而且还编码了一个包含一个对象的数组.但是该数组没有widrepid属性,只有数组中的对象具有!

Looks like your JSON encodes not simply one object, but an array containing one object. But that array doesn't have the wid and repid properties, only the object inside the array has!

尝试

  • {"wid":"2","repid":"1"}仅编码对象而不将其放入数组

  • {"wid":"2","repid":"1"} to encode just an object without putting it into an array or

obj[0]["wid"]访问数组中第一个(也是唯一的)对象的属性.

obj[0]["wid"] to access the properties of the first (and only) object in the array.

顺便说一句,如果您知道属性的名称,则应使用点表示法:obj[0].wid而不是obj[0]["wid"].

By the way, if you know the names of the properties, you should use dot notation: obj[0].wid instead of obj[0]["wid"].

这篇关于如何使用JavaScript从JSON对象提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆