0

我希望这是一个简单的noober问题。我从来没有真正玩过 JSON。我让我的文档使用 XML 拉取,但我正在努力尝试通过 JSON 请求正确解析它。

我会让我遇到的问题尽可能简单。以下是我正在提取的 JSON 文档中的两个示例条目:

{
  "completed_in":0.386,
  "query":"%23c2alerts",
  "results":[
     {
        "author":{
           "namespace":"user",
           "name":"nichazel",
           "string_form":"user:nichazel",
           "full_name":"Nicholas Hazel"
        },
        "body":"Have an idea? We are trying to collect new and fresh ideas for process improvement. Please jot down ANY ideas you may have. We will discuss them in our team meeting this afternoon -urgent #c2alerts",
        "topics":[
           {
              "namespace":"hashtag",
              "name":"c2alerts",
              "string_form":"hashtag:c2alerts"
           }
        ],
        "source":"web",
        "post_id":"30d97e00-596f-4936-ade9-557db0e907df",
        "created":"2013-07-31T20:18:22Z",
        "votes":{
           "up_votes":2,
           "down_votes":0,
           "up_voters":[
              {
                 "namespace":"user",
                 "name":"bostrom",
                 "string_form":"user:bostrom"
              },
              {
                 "namespace":"user",
                 "name":"eakerry",
                 "string_form":"user:eakerry"
              }
           ],
           "down_voters":[

           ]
        }
     },
     {
        "author":{
           "namespace":"user",
           "name":"chayavic",
           "string_form":"user:chayavic",
           "full_name":"Sam Chayavichitsilp"
        },
        "body":"Happy Friday C2. Retail AHOD (L2) - No Stand-Up Meeting for the entire team.\n#c2alerts",
        "topics":[
           {
              "namespace":"hashtag",
              "name":"c2alerts",
              "string_form":"hashtag:c2alerts"
           }
        ],
        "source":"web",
        "post_id":"a05d96ae-2c6e-4054-989f-d25a74bfc553",
        "created":"2013-07-26T14:57:18Z"
     }
  ]
}

假设我只是想将“名称”和“正文”附加到 HTML 文档。我正在努力弄清楚如何仅使用 JSON 文档的一部分创建一个数组。

Javascript:

<script>
    $(function(){
        $.getJSON('json.json',function(data){
            console.log( "Name: " + name[0].name );
            console.log( "Body: " + body[0].body );

        });
</script>

我知道这不是任何功能,但是如何定义要在数组中收集的部分,以便可以将它们定义为变量?感谢任何帮助,因为我读过的所有 W3C 学校和论坛似乎都没有识别出这样的简单方法。

完美的例子:

姓名:nichazel 身体:有想法吗?我们正在努力收集新的和新鲜的想法来改进流程。请记下您可能有的任何想法。我们将在今天下午的团队会议上讨论它们-紧急#c2alerts

名称:chayavic 身体:Happy Friday C2。零售 AHOD (L2) - 整个团队没有站立会议。#c2alerts

4

1 回答 1

1

要获得第一个结果nameand body,那么您需要这样做:

results[0].author.name;
results[0].body;

要遍历所有结果,请执行以下操作:

$.each(data.results, function(i, item) {
    alert(item.author.name);
    alert(item.body);
});​
于 2013-08-05T20:30:03.090 回答