-2

I have the following JSON object (accessed through item):

enter image description here

I don't know why this is stumping me, but to access the values of divisions, I would do either item.divisions or item["divisions"], right? I'm getting undefined when I try both of those options. What's going on? Am I not accessing the data correctly?

Aaand, here it is:

//options has information like hostname, path, etc.
var req = https.request(options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (item) {
    console.log(item); //this is the JSON that you're seeing
    console.log(item.kind); //undefined
  });
});
patrickhuang94
  • 2,085
  • 5
  • 36
  • 58

2 Answers2

3

You need to parse the JSON into a Javascript object.

//options has information like hostname, path, etc.
var req = https.request(options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (response) {
    console.log(response); //this is the JSON that you're seeing
    item = JSON.parse(response);
    console.log(item.kind);
  });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I'm receiving an `SyntaxError: Unexpected end of input` and I think it's because I'm parsing an empty JSON: http://stackoverflow.com/questions/3983088/javascript-error-uncaught-syntaxerror-unexpected-end-of-input (2nd answer) – patrickhuang94 Oct 13 '16 at 09:25
  • If `console.log(response)` shows the JSON that you posted, then it's not empty JSON. – Barmar Oct 13 '16 at 09:26
  • It isn't an empty JSON, but when I parse it, the JSON stops halfway and throws the error. `typeof response` is showing up as string. – patrickhuang94 Oct 13 '16 at 09:29
  • jsonlint.com says the JSON is valid. – Barmar Oct 13 '16 at 09:31
  • I'd show you the screenshot of my terminal but I have no idea how to send that through the comments. – patrickhuang94 Oct 13 '16 at 09:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125577/discussion-between-homerboy-and-barmar). – patrickhuang94 Oct 13 '16 at 09:33
  • Don't post screenshots, copy and paste plain text into the question. Mark it as code with the `{}` tool in the SO editor. – Barmar Oct 13 '16 at 09:33
0

I think your problem can be solved like this ,

var x = "YOUR JSON"

x.divisions gives you the object

Object {ocd-division/country:us/state:me/sldl:141: Object, ocd-division/country:us: Object, ocd-division/country:us/state:me/county:washington/council_district:1: Object, ocd-division/country:us/state:me/cd:2: Object, ocd-division/country:us/state:me/place:princeton: Object…}

Your key has string and your value is Object

You can further access it like

var p = x.divisions

 for (var key in p) {
  if (p.hasOwnProperty(key)) {
    console.log(key + " -> " + p[key]);
  }
}

Hope it helps !!

Mandeep Singh
  • 1,287
  • 14
  • 34