我希望这是一个简单的noober问题。我从来没有真正玩过JSON。我让我的文档使用XML pull,但我正在努力尝试通过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"
}
]
}
让我假装我只想将“name”和“body”附加到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 身体:周五快乐C2。零售AHOD(L2) - 整个团队没有站立会议。 #c2alerts
答案 0 :(得分:1)
要获得第一个结果name
和body
,您需要执行此操作:
results[0].author.name;
results[0].body;
要遍历所有结果,请执行以下操作:
$.each(data.results, function(i, item) {
alert(item.author.name);
alert(item.body);
});