1

Here is the situation:

I have a Rails app that scrapes a website and outputs valid JSON to a restful API endpoint.

So far I can get the JSON with my Node.js script, but I cannot store the values I need to local variables.

Here is the json:

[{"cohort":"1507","teacher":"Josh M."}]

I would like to store "1507" in a variable as well as "Josh M."

My current script is:

var http = require('http');
var url = 'http://localhost:8080/api/v1/classroom_bs';

http.get(url, function(res){
    var body = '';

    res.on('data', function(chunk){
        body += chunk;
    });

    res.on('end', function(){
        var responseB = JSON.parse(body);
        var responseBStr = JSON.stringify(body);
        var jsonB = JSON.parse(responseBStr);
        console.log(responseB);
        console.log(responseBStr);
        console.log(jsonB);
    });
}).on('error', function(e){
      console.log("Error: ", e);
});

Any help would be greatly appreciated!

I have tried some functions I found on SO, but for some reason all my console.log(Object.keys) return numbers like "1", "2", "3", etc..

The reason I need to store these as variables is that I am going to output those values to an LCD screen using the johnny5 library via an Arduino.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • 1
    The `Object` – `{...}` – is nested within an Array – `[...]`. To reach the Object, you'll have to first access an index of the Array – `responseB[0].cohort`. For more info: [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Jonathan Lonowski Nov 07 '15 at 18:29
  • That makes complete sense. Let me mess around some more and then I will let you know! –  Nov 07 '15 at 18:40
  • The answer below totally worked, but it uses the same logic. Thanks! –  Nov 07 '15 at 18:44

2 Answers2

0

Try selecting object at index 0 of parsed json string

var response = '[{"cohort":"1507","teacher":"Josh M."}]';

var responseB = JSON.parse(response);

var keys = Object.keys(responseB[0]);

var cohort = responseB[0][keys[0]];

var teacher = responseB[0][keys[1]];

console.log(cohort, teacher)
guest271314
  • 1
  • 15
  • 104
  • 177
0

The rails app that you are using to send to node is an array of length 1, which is an object. To access that object you have to say which array element you are accessing. In this case array[0]. It appears your rails scraper is populating an array.

To access the variables you mentioned you would simply

    //Access that 1507
    var variable1 = payloadFromRails[0].cohort;
    //Access that teach, Josh M.
    var variable2 = payloadFromRails[0].teacher;
Zenkylo
  • 136
  • 6