0

I have been trying to read the values of a simple JSON array I wrote in Java, in Javascript. None of my experiments have seemed to work, though. I've tried accessing these values as suggested by seemingly "duplicate" Stack Overflow posts. Link1 Link2 Link3 Link4

JSON

{"Year":["2023","2027","2031","2035","2039","2043","2047","2051","2055","2059","2063","2067"],"CO2":[417.06933333333336,423.9074666666667,430.7456000000001,437.5837333333334,444.42186666666674,451.2600000000001,458.0981333333334,464.93626666666677,471.77440000000007,478.61253333333343,485.4506666666668,492.2888000000001]}

JAVASCRIPT

<script type="text/javascript">

var json = JSON.parse("FutureAtCurrentRate.json");
alert(json[0].Year);
alert(json[0].CO2);
alert(json["Year"][0]);
alert(json["CO2"][0]);
alert(json[0]["Year"]);
alert(json[0]["CO2"]);
alert(json.Year);
alert(json.CO2);
</script>

So, I have all these alerts in the script, yet no alert box shows when I run it on a HTML page. The json file is saved in the same folder directory as the .jsp file.

  • your JSON is an object, you are attempting to access it as an array, so the first line `json[0].Year` breaks it and you get a reference error, stopping the rest from firing. Developer console would give you this error, always check the console before posting. – Dellirium Feb 16 '19 at 22:09
  • Thank you for your feedback. Although I did not check developer console, and I will make sure to to in the future, I did test each alert individually (by commenting out the others) to no avail. – Gracen Ownby Feb 16 '19 at 22:29
  • Upon looking more closely, your issue is even before any alert, the `JSON.parse` expects a valid JSON string, what you gave it was "FutureAtCurrentRate.json" which is definitively not a valid JSON. – Dellirium Feb 17 '19 at 20:19
  • Thank you, I figured this out some time last night and pondered what to do next. I modified my code to call JSON.parse(JSON.stringify(".json")) and it seems to fix that error. Now I am having issues accessing the data in that JSON string. – Gracen Ownby Feb 17 '19 at 22:19

0 Answers0