Undool Sipper
Undool Sipper

Reputation: 55

Indexing nested JSON in Node.js

I'm having difficulty figuring out how to index in JSON.

Here is an example JSON that is similar to what I am working with:

 {
    "Customers": [
        {
          "FieldOne": 0,
          "FieldTwo": {
               "Blah": "233223",
               "Target": "GOAL"
           }
         }
       ]
    }

How would I go about getting the target property?

I've tried this:

var unparsed = JSON.stringify(body)
var data = JSON.parse(unparsed)
var tgt = data.Customers.FieldTwo.Target

But it doesn't work and tells me that it is undefined

Upvotes: 1

Views: 2819

Answers (1)

Endenite
Endenite

Reputation: 390

Since data.Customers is an array containing the customer object, you'll need to access data.Customers[0].FieldTwo.Target instead of data.Customers.FieldTwo.Target. Example:

var tgt = data.Customers[0].FieldTwo.Target

Notice that body is JSON object, not a string in this code sample:

var body = 
{
    "Customers": [{
        "FieldOne": 0,
        "FieldTwo": {
            "Blah": "233223",
            "Target": "GOAL"
        }
    }]
}
;

var unparsed = JSON.stringify(body);
var data = JSON.parse(unparsed);
var tgt = data.Customers[0].FieldTwo.Target;
document.write(tgt);

But here body is a string, so there is no need to stringify it:

var b = 
`{
    "Customers": [{
        "FieldOne": 0,
        "FieldTwo": {
            "Blah": "233223",
            "Target": "GOAL"
        }
    }]
}`
;

// var unparsed = JSON.stringify(b);  <-- no need to stringify
var data = JSON.parse(b);
var tgt = data.Customers[0].FieldTwo.Target;
document.write(tgt);

Upvotes: 2

Related Questions