1

I have a database server that will be running a script to generate this given file daily:

{"data": [
{"variable":"var1","value": "123"},
{"variable":"var2","value": "456"},
{"variable":"var3","value": "789"}]}

I am trying to parse this file to set three javascript variables for a HTML canvas element.

So far, I'm thinking I'll parse the JSON file

var JSONfile = './file.json';
var getData = JSON.parse(JSONfile);

Then a for loop to assign the variables

for (i = 0; i < getData.length; i++) {
    var getData.variable=getData.Value;
}

And I'm hoping to get results of:

var var1 = 123;
var var2 = 456;
var var3 = 789;

But var getData.variable=getData.Value; breaks. What am I missing?

4
  • 4
    The JSON.parse() API expects a string containing JSON syntax, not the name of a file. Commented Mar 25, 2015 at 18:43
  • @Pointy is correct ... you need to do an AJAX call to get the JSON contents, then parse the contents returned from that call. Commented Mar 25, 2015 at 18:44
  • try using $.getJSON({'url',parameter,callback}); [api.jquery.com/jquery.getjson/] Commented Mar 25, 2015 at 19:03
  • $.getJSON('test.json', function(data) { $.each(data.JSONdata, function(i, f) { var f.number = f.value; }); }); It still breaks on var f.number... unexpected token . How can I set a variable name to a value from the object? Commented Mar 25, 2015 at 19:15

1 Answer 1

1

JSON.parse() expects a JSON string, when you are passing it a file.

The first thing you need to do is use AJAX to get the contents of the file into a variable. Either use a library like jQuery (see http://api.jquery.com/jquery.getjson/) or from scratch in JavaScript. But don't waste your time on the "from scratch" version unless you have to.

Use jQuery to get the contents of the file into an object, and pass the inner data (an array) to a function called doSomething():

    $(function () {
        $.getJSON("./file.json", function (data) {
        }).success(function (data) {
            myArr = data.data;
            doSomething(data.data);
        });
    });

Here, you iterate through the passed array, which contains elements that have a .variable and a .value property. This writes both properties of each element to the console, for your viewing pleasure:

    function doSomething(arr) {
        for (i = 0; i < arr.length; i++) {
            console.log(arr[i].variable + ': ' + arr[i].value);
        }
    }

You can also access the properties directly by the index as follows:

alert(jsonFromFile.data[2].variable);  // Will alert "var3"
alert(jsonFromFile.data[2].value);     // Will alert "789"
Sign up to request clarification or add additional context in comments.

9 Comments

Got most of that working. Is there a way to assign both the variable name and value from the JSON? var jsonFromFile.data[i].variable = jsonFromFile.data[i].value
I've updated my answer to include the ajax call and accessing both .variable and .value properties of each array element.
I continue to get an Unknown Token . error when trying to name a variable with the properties. var jsonFromFile.data[i].variable = jsonFromFile.data[i].value is what gives the error.
var jsonFromFile.data[i].variable = jsonFromFile.data[i].value attempts to overwrite the .variable with the .value. Is that what you want to do? I would think your goal would be to extract the contents out of jsonFromFile into something more useful that you use to do the rest of your work with. Perhaps if I knew what you do with the values after retrieving them, I could suggest how to go about it.
as opposed to setting var1 = 123 var2 = 456 var3 = 789 manually I want to set those three variable names and values from the JSON file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.