Correctly load and parse a JSON file with javascript

140 Views Asked by At

I am trying to load and manipulate a JSON file in Javascript however, when i load the json like so:

var my = $.getJSON("../file.json");
console.log('my (before) :', my);

for(var i=0; i<my.length; i++) {
    my[i]["Value" + my[i].Year] = my[i].Value;
    delete my[i]["Value"];
}

console.log('my (after) :', my);

The JSON is unchanged. The opposite happens when i load JSON like so:

var chartDataSource = [
        {
            "Month": "August",
            "Value": 1176124,
            "Year": 2012
        },
        {
            "Month": "December",
            "Value": 1205852,
            "Year": 2012
        }];

The for loop correctly performs the changes into the data structure.

credit for the loop goes to

1

There are 1 best solutions below

1
AlexanderBrevig On BEST ANSWER

Check this: http://api.jquery.com/jquery.getjson/

Your var me is probably not populated with data. Try this:

$.getJSON("../file.json", function(my){
  console.log('my (before) :', my);

  for(var i=0; i<my.length; i++) {
    my[i]["Value" + my[i].Year] = my[i].Value;
    delete my[i]["Value"];
  }

  console.log('my (after) :', my);
});

And be sure to check that your server is configured to return the value of ../file.json as text. Likely F12 in your browser will reveal if the file is served.