Search code examples
javascriptjsonajaxxmlhttprequest

JavaScript - Read Json if first value if is Zero


I have a Json file like this

{
"0":{
    "poperty1":"poperty1",
    "poperty2":"poperty2",
    },
"1":{
    "poperty1":"poperty1",
    "poperty2":"poperty2",
    },
"2":{
    "poperty1":"poperty1",
    "poperty2":"poperty2",
    },
}

And i read it with this function:

function readJson(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "file.json", false);
rawFile.onreadystatechange = function ()
{
    if(rawFile.readyState === 4)
    {
        if(rawFile.status === 200 || rawFile.status === 0)
        {
            // console.log(JSON.parse(rawFile.responseText));
        }
    }
};
rawFile.send(null);
return JSON.parse(rawFile.responseText);
}

But it return every value exept the 0

"1":{
    "poperty1":"poperty1",
    "poperty2":"poperty2",
    },
"2":{
    "poperty1":"poperty1",
    "poperty2":"poperty2",
    }

even if i removit and start the json with 1 it return the 1 as well.

so any idea why?


Solution

  • Edit

    I updated your JSON on github, and I tested both the XHR response and the parsed object, in order to check that is correct, and I can say for sure it works properly:

    function readJson(){
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", "https://raw.githubusercontent.com/crisz/file/master/file.json", false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status === 0)
            {
                console.log(JSON.parse(rawFile.responseText));
            }
        }
    };
    rawFile.send(null);
    // return JSON.parse(rawFile.responseText);
    }
    
    readJson();

    In the previous answer I hadn't notice the return inside the asynchronous function, if you have doubts about how asynchronous functions work in Javascript, you can check this answer.

    Old answer

    Your JSON is malformed. The JSON specification doesn't expect a comma at the end of the last key-value of a set.

    Remove the trailing commas, and the parsing will work:

    {
    "0":{
        "poperty1":"poperty1",
        "poperty2":"poperty2"
        },
    "1":{
        "poperty1":"poperty1",
        "poperty2":"poperty2"
        },
    "2":{
        "poperty1":"poperty1",
        "poperty2":"poperty2"
        }
    }
    

    If also removing commas you have still problems in the resulting object, then try testing your API endpoint to see if the response is what you expect.