How to alert json file data from javascript

后端 未结 3 683
醉酒成梦
醉酒成梦 2020-12-05 14:14

How can I alert the below JSON code using jquery?

{
    \"results\": {
        \"course\": \"CC167\",
        \"books\": {
                     


        
相关标签:
3条回答
  • 2020-12-05 14:36

    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));
    
    0 讨论(0)
  • 2020-12-05 14:48
    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.

    0 讨论(0)
  • 2020-12-05 14:50

    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.

    0 讨论(0)
提交回复
热议问题