如何从JSON响应中访问键值

时间:2017-06-10 15:10:09

标签: javascript json node.js

我在发送短信后尝试从Twilio的JSON响应中获取siddate_created,但它们始终为undefined

我还尝试了body.['sid']body.['date_created'],但他们仍然没有返回正确的值。

代码

const textMe = function sendSms() {
  request.post(options, (err, resp, body) => {
    if (err) {
      console.log('error:', err);
    } else {
      console.log('statusCode:', resp.statusCode);
      console.log('sid:', body.sid);
      console.log('dateCreated:', body.date_created);
    }
  });
};

textMe();

期望

statusCode: 201
sid: SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
dateCreated: Sat, 10 Jun 2017 14:55:14 +0000

现实

statusCode: 201
sid: undefined
dateCreated: undefined

来自console.log(正文)的JSON响应

{"sid": "SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "date_created": "Sat, 10 Jun 2017 14:55:14 +0000", "date_updated": "Sat, 10 Jun 2017 14:55:14 +0000", "date_sent": null, "account_s
id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "to": "+xxxxxxxxxxxx", "from": "+xxxxxxxxxxxx", "messaging_service_sid": null, "body": "Sent from your Twilio trial account - Twilio Test using
Node.js and request.", "status": "queued", "num_segments": "1", "num_media": "0", "direction": "outbound-api", "api_version": "2010-04-01", "price": null, "price_unit": "USD", "error_cod
e": null, "error_message": null, "uri": "/2010-04-01/Accounts/xxxxxxxxxxxx/Messages/xxxxxxxxxxxx.json", "subresource_uris": {"media": "/2010-0
4-01/Accounts/xxxxxxxxxxxx/Messages/xxxxxxxxxxxx/Media.json"}}

编辑:

工作代码

const textMe = function sendSms() {
  request.post(options, (err, resp, body) => {
    if (err) {
      console.log('error:', err);
    } else {
      console.log('statusCode:', resp.statusCode);
      console.log('sid:', JSON.parse(body).sid);
      console.log('dateCreated:', JSON.parse(body).date_created);
    }
  });
};

textMe();

1 个答案:

答案 0 :(得分:0)

你的身体仍然是字符串吗?如果是这样,您将需要JSON.parse(body)来访问JSON对象中的属性。