Parsing JSON file and using it in HTML

This question already has an answer here:

  • Parse JSON in JavaScript? [duplicate] 16 answers

  • Assuming the file resides along with your html and css files. You would first need to get it into your current page with the <script> tag. Also if you want to be able to access all the objects in the .json file then it would be easier to wrap the entire file content in a variable either as an array (shown below) or a parent object,

    var myObj = [
        {
            "number": "001",
            "name": "Jill",
            "date": "2014. January 01."
        },
        {
            "number": "002",
            "name": "John",
            "date": "2014. March 03."
        }
    ]
    

    then in the file you are accessing this from you could place its contents in a div with something like this,

    document.getElementById('divId').innerHTML = myObj[0].name;
    

    If on the other hand you are receiving this data from a server via an AJAX request as a text string then you may need to parse the received data via JSON.parse() before accessing the content.


    循环播放json,如下所示:

    var obj = [{
    "number": "001",
    "name": "Jill",
    "date": "2014. January 01."
    },
    {
    "number": "002",
    "name": "John",
    "date": "2014. March 03."
    }];
    
    obj.forEach(function(v,k){
        alert(v.name);
    });
    

    You need to parse the JSON string to an object:

    var theJSONstring; //your JSON contents from the file
    var jsonObject = JSON.parse(theJSONstring);
    

    You can probably access the items like this:

    var secondNumber = jsonObject[1].number  //"002"
    
    链接地址: http://www.djcxy.com/p/8500.html

    上一篇: JQuery的JSON响应是未定义的

    下一篇: 解析JSON文件并在HTML中使用它