问题描述
以下是我使用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"}]
提取wid
和repid
的值,我在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"];
但是我正在将a
和b
的值作为undefined
而不是2
,1
but I'm getting value for a
and b
as undefined
instead of 2
,1
推荐答案
看起来您的JSON不仅编码了一个对象,而且还编码了一个包含一个对象的数组.但是该数组没有wid
和repid
属性,只有数组中的对象具有!
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对象提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!