我将数据带入json
字符串,该字符串在我的下面代码中显示为r.d
。
现在我想访问它的字段。那我该如何访问呢?
这是代码
$.ajax({
url: "GET_DATA_BY_STORE.aspx/GETSTOREINFO",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ STORE_ID: STORE_ID }),
async: true,
processData: false,
cache: false,
success: function (r) {
alert(getJSONValue[0].STORE_ID);
},
error: function (xhr) {
// alert('Error while selecting list..!!');
}
})
在r.d
中我将数据作为
答案 0 :(得分:1)
使用JSON.parse将其转换为json对象后,您可以像访问javascript对象一样访问属性:
var jsonString = '{"d": [{"field1": "value1", "field2": 15.0}, {"field3": [1,2,3]}]}'
var r = JSON.parse(jsonString)
console.log(r.d)
// output: [ { field1: 'value1', field2: 15 }, { field3: [ 1, 2, 3 ] } ]
console.log(r.d[0].field1)
// output: value1
console.log(r.d[0].field2)
// output: 15
console.log(r.d[1].field3)
// output: [ 1, 2, 3 ]
// you can also use brackets notation to access properties in object
console.log(r.d[0]["field1"])
// output: value1
// or you can iterate properties if the data type of a field is an array (r.d is an array)
r.d.forEach(function(prop) {
console.log(prop);
})
// output: { field1: 'value1', field2: 15 }
// { field3: [ 1, 2, 3 ] }