Mdurocher
Mdurocher

Reputation: 53

JSON Parsing Specific Values

I am trying make an GET request and then parse the body response, which is in JSON, in order to print out individual values of the body.

In this example I have a helpdesk ticket and I want to get the individual tickets subject field. I can get the response and the ticket with all values included (shown below) but I can not specify to only print the subject field.

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    const info = JSON.parse(body);
    console.log(info.tickets);
  }
}

This first section works fine and I get the following response.

[ { deleted: false,
    status: 1,
    tags: [],
    subscribers: [ [Object] ],
    _id: '5d9bd7cbce54bb059eaa8917',
    subject: 'Laptop Slow',
    group:
     { members: [Array],
       sendMailTo: [],
       public: false,
       _id: '5d976626c2547f37e092b2ee',
       name: '02719',
       __v: 2 },
    type:
     { priorities: [Array],
       _id: '5d9247605ab9ee056952fe39',
       name: 'Issue',
       __v: 2 },
    priority:
     { overdueIn: 2880,
       htmlColor: '#29b955',
       _id: '5d9247689701551f588adf76',
       name: 'Normal',
       migrationNum: 1,
       default: true,
       __v: 0,
       durationFormatted: '2 days',
       id: '5d9247689701551f588adf76' },
    issue: '<p>Hi My laptop is really slow</p>\n',
    date: '2019-10-08T00:26:51.301Z',
    comments: [],
    notes: [],
    attachments: [],
    history: [ [Object], [Object], [Object] ],
    owner:
     { _id: '5d978f80f5d1fd428f32570b',
       username: 'test-customer',
       email: '[email protected]',
       fullname: 'Test-Customer',
       title: '',
       role: [Object] },
    uid: 1002,
    __v: 2,
    closedDate: null } ]

However, when I try and go one field further (i.e. info.tickets.subject), I receive undefined for the subject value.

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    const info = JSON.parse(body);
    console.log(info.tickets.subject);
  }
}

undefined

Upvotes: 0

Views: 150

Answers (2)

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5600

Your Data is an array in your database query u are using find you should use findOne then you code work properly.

For find Query

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    const info = JSON.parse(body);
    console.log(info.tickets[0].subject);
  }
}

For findOne Query

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    const info = JSON.parse(body);
    console.log(info.tickets.subject);
  }
}

Upvotes: 1

Phong Nguyen
Phong Nguyen

Reputation: 150

info.tickets is an array, you can not access as a object.

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    const info = JSON.parse(body);
    console.log(info.tickets[0].subject);
  }
}

Upvotes: 2

Related Questions