如何将以下JSON数据打印为HTML表格:
{"response":
{"tweets":
[{"ID":"718045120386441216","TDate":"Thu Apr 07 11:57:51 +0000 2016",
"FormerPlace":
{"id":"07e9c7d1954fff64","url":"https://api.twitter.com/1.1/geo/id/07e9c7d1954fff64.json","place_type":"city","name":"Sheffield","full_name":"Sheffield, England","country_code":"GB","country":"United Kingdom","contained_within":[],"bounding_box":{"type":"Polygon","coordinates":[[[-1.573648,53.309898],[-1.325576,53.309898],[-1.325576,53.4564311],[-1.573648,53.4564311]]]},"attributes":{}},
"Label":"@brain4_digital Let us go to #Italy @abdulazizDhafer",
"InReplyTo":
{"ID":"699983775007170560","ScreenName":"brain4_digital","UserID":"4909086905"},
"UserMentions":
[{"ID":"4909086905","ScreenName":"brain4_digital","Name":"Digital Brain"},{"ID":"305152994","ScreenName":"abdulazizDhafer","Name":"عبدالعزيز العمري"}],
"Hashtags":["Italy"],
"User":
{"ID":"707943702623338497","ScreenName":"NasserPshko","Name":"Nasser","Location":"","Link":"http://pbs.twimg.com/profile_images/707951652515532800/N-bWyjg9_normal.jpg"}
}],
"stats":
{"topUsers":[{"user":"NasserPshko","count":1,"topWords":[{"word":"@brain4_digital","count":1},{"word":"Let","count":1},{"word":"us","count":1},{"word":"go","count":1},{"word":"#Italy","count":1}]}],"topWords":[{"word":"@brain4_digital","count":1},{"word":"Let","count":1},{"word":"us","count":1},{"word":"go","count":1},{"word":"#Italy","count":1},{"word":"@abdulazizDhafer","count":1}]}}}
首先,我尝试将JSON中的每个元素打印为:
var arr=JSON.parse(response.responseText);
for (var i in arr){
alert(arr.response[i].tweets);
}
它并没有奏效。有没有其他方法可以单独打印每个JSON值?
答案 0 :(得分:0)
无法绕过你真正想要的东西,所以我做了一些如何使用特定JSON文档的例子。
var arr = JSON.parse(text);
console.log(arr);
/** Navigating inside the response, selecting the tweets **/
var tweets = arr.response.tweets;
console.log(arr.response.tweets);
/** Looping through the different properties of a tweet **/
for(var i = 0; i < tweets.length; i++){
console.log(tweets[i]);
/** Here you can set a property to some HTML element. I.e. the date **/
console.log(tweets[i].TDate);
}
首先要做的事情:将响应解析为JSON,即您已经管理过的。然后你必须使用点符号(即someProperty.somePropertyOnAnotherLevel
)浏览解析的json。
然后我们最终得到了我认为是你问题的一部分:迭代不同级别的属性:使用标准for-loop
迭代它的所有属性。