End goal: from a given URL (assume same server/domain) that contains some data in this form:
{"foo":6481,"value":13,"thing":"12_3"}
Get JavaScript code to read the data and put it into an array/object so that it can be used to plot the "value" on a graph. The server will automatically update the link with new data, but for now just trying to figure out how to access "value"
To test, I created a .json file and an .html file and am just trying to print '13' from "value" to see how I can access it, but am having trouble getting anything to work. I've spent MANY hours on stack overflow and google trying to figure this out. This is the closest thing to what I thought could help me: How to create JAVASCRIPT ARRAY from external file JSON, but it isn't working
What I've tried for datadata.json:
{"foo":6481,"value":13,"thing":"12_3"}
[{"foo":6481,"value":13,"thing":"12_3"}]
'[{"foo":6481,"value":13,"thing":"12_3"}]'
then for my JS file:
var newArray = new Array ();
$.ajax({
async: false,
url: 'datadata.json',
data: "",
accepts: 'application/json',
dataType: 'json',
success: function(data) {
newArray.push(data.value); //or data.name
}
})
console.log(newArray);
This will print empty brackets, and this error: SyntaxError: Unexpected token ':'. Parse error.
Also tried XMLHttpRequest which results in same error:
var jsonArr = new XMLHttpRequest();
jsonArr.open('GET', 'datadata.json', true);
jsonArr.onreadystatechange = function(data) {
console.log(jsonArr.name);
};
jsonArr.send();
When the .json file data has a name for the array:
data = '[{"foo":6481,"value":13,"thing":"12_3"}]'
using JSON.parse(data) works.
Why is this and how can I get the data to parse from a URL?
Also, I do NOT want to use PHP for this.
---Working solution, but still with error for .json file---
var myArray = new Array ();
$.getJSON( "datadata.json", function( data ){
myArray = data;
console.log(myArray.value);
});
using this format:
{"foo":6481,"value":13,"thing":"12_3"}