22 javascript json
如何使用jquery提醒下面的JSON代码?
{
"results": {
"course": "CC167",
"books": {
"book": [
{
"-id": "585457",
"-title": "Beginning XNA 20 game programming : from novice to professional",
"-isbn": "1590599241",
"-borrowedcount": "16"
},
{
"-id": "325421",
"-title": "Red Hat Linux 6",
"-isbn": "0201354373",
"-borrowedcount": "17"
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的json文件内容,可以命名result.json.我需要使用JavaScript或jQuery提醒或打印此文件的所有数据.我怎样才能做到这一点 ?
azz*_*azz 36
让我们假设你有字符串中的JSON, var json_str = '{ "results": ... }';
从那里你必须将其解析为JSON,这可以使用:
var json_obj = JSON.parse(json_str);
Run Code Online (Sandbox Code Playgroud)
如果您需要从文件加载,请使用:
var json_obj;
$.getJSON("result.json", function (data) {
json_obj = data;
});
Run Code Online (Sandbox Code Playgroud)
拥有JSON对象后,访问数据非常简单.
alert(json_obj.results.books.book[1]["-title"]); >>> Red Hat Linux 6
Run Code Online (Sandbox Code Playgroud)
或者打印JSON作为一个整体:
alert(JSON.stringify(json_obj));
Run Code Online (Sandbox Code Playgroud)