0

给定这样的json:

{ "rss": {
   "page": 1,
   "results": [{
      "type": "text",
      "$": 10
   }],
   "text": [{
      "content": "Lorem ipsum dolor sit amet.",
      "author": {
         "name": "Cesar",
         "email": "cesar@evoria.com"
      },
   },
   {
      "content": "Tema Tis rolod muspi merol.",
      "author": {
         "name": "Cleopatre",
         "email": "cleopatre@pyramid.com"
      },
   }]
}

在 javascript 中,我可以像这样检索值:

var json = JSON.parse(datajson);
$.each(json.text, function(key, val) {
    // this one is ok
    var content = val['content'];
    // this one does not work
    var authorname = val['author.name'];
});

这是一种方式,给定字符串格式的属性名称,检索复杂对象的值,例如json.text[0].author.name

编辑 我想将所需的属性存储在另一个对象中,例如:

[
    { dt: "Text content", dd: "content" },
    { dt: "Author name", dd: "author.name"}
]
4

3 回答 3

3

您可以按“段”拆分“索引”.并循环遍历“段”,在每次迭代时按级别递减。

var obj = {
   author : {
      name : "AuthorName"
   }
}

function get_deep_index(obj, index) {   
   var segments = index.split('.')
   var segments_len = segments.length
   var currently_at = obj
   for(var idx = 0; idx < segments_len; idx++) {
      currently_at = currently_at[segments[idx]]
   }
   return currently_at
}

console.log(get_deep_index(obj, 'author.name'))
于 2012-07-23T15:12:17.493 回答
2

以下应该可以解决问题。

var authorname = val['author']['name'];

您还可以将对象本身存储为:

var author = val['author'];

然后稍后您可以从中索引属性。

console.log(author.name, author.email)
于 2012-07-23T14:51:16.797 回答
-2

Yent 用 eval 函数在评论中给出了很好的提示。我用这种代码解决了我的需要:

var json = JSON.parse(myjsonasastring);

var descriptiontobeadded = [
    { dt: "Text content", dd: "content" },
    { dt: "Author name", dd: "author.name" }
];

$.each(descriptiontobeadded, function(key, val) {
    var dt = '<dt>' + val.dt + '</dt>';
    description.append(dt);
    var dl = '<dd>' + eval('json.' + val.dd) + '</dd>';
    description.append(dl);
});
于 2012-07-23T15:02:44.820 回答