1

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"}
Community
  • 1
  • 1
matcha
  • 81
  • 1
  • 9
  • 1
    By overriding the callback results for test reasons [it works correctly](http://jsfiddle.net/yk2kg31v/). As a general rule though, synchronous AJAX requests are a bad idea for UX.. – scrowler Jun 25 '15 at 00:47
  • 1
    @scrowler, I believe you mean synchronous :) – Patrick Evans Jun 25 '15 at 00:49
  • 1
    @scrowler, thank you, from my research, $.getJSON is equivalent to using $.ajax code, is that correct? Also, async would be set to true by default using $.getJSON? I had forgotten what async was, but read about it again after your comment – matcha Jun 25 '15 at 01:33
  • 1
    Yeah, or even just `$.get()` would do nicely – scrowler Jun 25 '15 at 01:36

0 Answers0