我有这样的json:
[{"pk": 1, "fields": {"name": "name 1", "description": "description 1", "image": "absolute url 1"}, "pk": 2, "fields": {"name": "name 2", "description": "description 2", "image": "absolute url 2"}}]
我需要访问字段,例如
$.getJSON("/json/", function(data) {
$.each(data, function(key, value) {
$.('#id1').append([data.pk]);
$.('#id2').append([data.fields.name]);
答案 0 :(得分:1)
您的代码中存在多个错误。你的JSON也是格式错误的。
var data = [{
"pk": 1,
"fields": {
"name": "name 1",
"description": "description 1",
"image": "absolute url 1"
},
"pk": 2,
"fields": {
"name": "name 2",
"description": "description 2",
"image": "absolute url 2"
}
}];
它只有一个具有多个相似属性的对象,最后一个相似属性会覆盖前一个属性,这意味着对象的pk
属性例如设置为2.它可能是应该有这个结构(一个包含2个对象的数组):
var data = [
{
"pk": 1,
"fields": {
"name": "name 1",
"description": "description 1",
"image": "absolute url 1"
}
},
{
"pk": 2,
"fields": {
"name": "name 2",
"description": "description 2",
"image": "absolute url 2"
}
}];
现在,您可以阅读对象'属性这样:
$.each(data, function (index, value) {
console.log("pk: ", value.pk);
console.log("fields.name: ", value.fields.name);
});
另请注意,要创建jQuery对象,您应删除.
:
$('#id1').append(value.pk);