简体   繁体   English

如何从javascript中提醒json文件数据

[英]How to alert json file data from javascript

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 . 这是我的json文件内容,可以命名为result.json I need to alert or print all data of this file using JavaScript or jQuery. 我需要使用JavaScript或jQuery提醒或打印此文件的所有数据。 How can I do this ? 我怎样才能做到这一点 ?

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));
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进行字符串化,你可以在浏览器的控制台中看到它。

Where do you get your json file from? 你从哪里得到你的json文件? Is it included somewhere on your page? 它是否包含在您页面的某个位置? If so, simply put it into a JS variabl and use it. 如果是这样,只需将其放入JS变量并使用它。 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). 如果它是服务器上的另一个文件,请使用jquery加载文件并在成功时实现回调(例如,请参阅jquery文档以获取jquery.getJSON)。 To stringify your json object, JSON.stringify (which should be build in). 要对json对象进行字符串化,JSON.stringify(应该是内置的)。 If you want to support all browsers, get the Json2 library which has a parse and stringify method. 如果要支持所有浏览器,请获取具有parse和stringify方法的Json2库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM