简体   繁体   中英

How to alert json file data from javascript

How can I alert the below JSON code using jquery?

{
    "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 ?

Lets assume you have the JSON in String, var json_str = '{ "results": ... }';

From there you have to parse it as JSON, this can be done using:

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.

alert(json_obj.results.books.book[1]["-title"]); >>> Red Hat Linux 6

Or print the JSON as a whole:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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