-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
  });
});
8
  • Check if that is actual JSON or string Commented Oct 13, 2016 at 8:58
  • Are you sure that the divisions variable is actually defined and contains data? Commented Oct 13, 2016 at 8:59
  • validate your JSON first, is it correct? Commented Oct 13, 2016 at 8:59
  • 2
    please paste the json instead of snapshot Commented Oct 13, 2016 at 9:01
  • 1
    You need to call JSON.parse() to convert the JSON into an object. Commented Oct 13, 2016 at 9:18

2 Answers 2

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);
  });
});
Sign up to request clarification or add additional context in comments.

7 Comments

I'm receiving an SyntaxError: Unexpected end of input and I think it's because I'm parsing an empty JSON: stackoverflow.com/questions/3983088/… (2nd answer)
If console.log(response) shows the JSON that you posted, then it's not empty JSON.
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.
jsonlint.com says the JSON is valid.
I'd show you the screenshot of my terminal but I have no idea how to send that through the comments.
|
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 !!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.