简体   繁体   中英

Reading values from JSON in Node.js in GET request

I need to pull the Indication value from the following

{
    "records": [{
        "id": "recBgV3VDiJeMkcwo",
        "fields": {
            "DrugName": "azatadine",
            "nameapi": ["recBgV3VDiJeMkcwo"],
            "Indication": "For the relief of the symptoms of upper respiratory mucosal congestion in perennial and allergic rhinitis, and for the relief of nasal congestion and eustachian t.b. congestion.",
            "lookup": ["azatadine"],
            "drugID": "recBgV3VDiJeMkcwo"
        },
        "createdTime": "2018-11-09T19:38:24.000Z"
    }]
 }

When I try to do response.records[0].fields.Indication I get the error Cannot read property 'fields' of undefined

Here is my code:

function httpGet() {

return new Promise(((resolve, reject) => {

var options = {

host: 'api.airtable.com',

port: 443,

path: '/v0/appYqfJ3Rt2F0sRGn/Database?filterByFormula=(DrugName=%27azatadine%27)',

method: 'GET',

headers: {

Authorization: 'Bearer key123456789'

}

};

const request = https.request(options, (response) => {

response.setEncoding('utf8');

let returnData = '';

response.on('data', (chunk) => {

returnData += chunk;

});

response.on('end', () => {

resolve(returnData);

});

response.on('error', (error) => {

reject(error);

});

});

request.end();

}));

}



const UserReplyIntent_Handler = {

canHandle(handlerInput) {

const request = handlerInput.requestEnvelope.request;

return request.type === 'IntentRequest' && request.intent.name === 'UserReplyIntent' ;

},

async handle(handlerInput) {

const response = await httpGet();

console.log(response);

return handlerInput.responseBuilder

.speak("Okay. Here we go" + response.records[0].fields.Indication)

.reprompt("say again")

.getResponse();

},

};

Your JSON isn't really JSON yet at this stage. You need to parse the result you get from your Ajax request to then work with it as native JSON.

The response is stringified when it gets delivered to you, that parse command will in stringify it for you.

You can do this as part of a then chain after your promise (probably best practice) or do it right inside your promise.

I was missing json.parse

.then((response) => {
      const data = JSON.parse(response);
 for (let i = 0; i < data.records.length; i++) {
 if (i === 0) {
     outputSpeech = outputSpeech +  'The name of the drug is' + data.records[i].fields.DrugName +  ', '

I was missing the json.parse method

.then((response) => {
      const data = JSON.parse(response);
 for (let i = 0; i < data.records.length; i++) {
 if (i === 0) {
     outputSpeech = outputSpeech +  'The name of the drug is' + data.records[i].fields.DrugName +  ', '

A standard way to do this with asynchronous responses is to do the following:

.then((response) => response.json())
.then((response) => {
  //response is now a JSON object that you can be worked with
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM