如何从javascript警告json文件数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18932686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to alert json file data from javascript
提问by azz
How can I alert the below JSON code using jquery?
如何使用 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"
}
]
}
}
}
This is my json file content which can named result.json. I need to alert or print all data of this file using JavaScript or jQuery. How can I do this ?
这是我的 json 文件内容,可以命名为result.json. 我需要使用 JavaScript 或 jQuery 提醒或打印此文件的所有数据。我怎样才能做到这一点 ?
回答by azz
Lets assume you have the JSON in String, var json_str = '{ "results": ... }';
让我们假设你有字符串中的 JSON, var json_str = '{ "results": ... }';
From there you have to parse it as JSON, this can be done using:
从那里你必须将它解析为 JSON,这可以使用:
var json_obj = JSON.parse(json_str);
If instead you need to load from a file, use:
如果您需要从文件加载,请使用:
var json_obj;
$.getJSON("result.json", function (data) {
json_obj = data;
});
Once you have the JSON object, it is simple to access the data.
拥有 JSON 对象后,访问数据就很简单了。
alert(json_obj.results.books.book[1]["-title"]); >>> Red Hat Linux 6
Or print the JSON as a whole:
或者打印整个 JSON:
alert(JSON.stringify(json_obj));
回答by Idan Magled
alert(JSON.stringify(result.json));
but you might like the
但你可能喜欢
console.log(result.json);
you dont need to stringify the json and you see it in the console of the browser.
你不需要对 json 进行字符串化,你可以在浏览器的控制台中看到它。
回答by MichaC
Where do you get your json file from? Is it included somewhere on your page? If so, simply put it into a JS variabl and use it. If it is another file on the server, use jquery to load the file and implement the callback on success (see jquery documentation for jquery.getJSON for example). To stringify your json object, JSON.stringify (which should be build in). If you want to support all browsers, get the Json2 library which has a parse and stringify method.
你从哪里得到你的 json 文件?它是否包含在您页面上的某处?如果是这样,只需将其放入 JS 变量并使用它。如果它是服务器上的另一个文件,请使用 jquery 加载文件并在成功时实现回调(例如,请参阅 jquery.getJSON 的 jquery 文档)。要将您的 json 对象字符串化, JSON.stringify (应该内置)。如果要支持所有浏览器,请获取具有 parse 和 stringify 方法的 Json2 库。

