简体   繁体   English

当我尝试 JSON.parse 时,获取 JSON 元素不起作用

[英]Getting JSON element is not working when I try JSON.parse

When console logging the event object using JSON.stringify(event) I get the below output.当控制台使用JSON.stringify(event)记录事件 object 时,我得到以下 output。

 {
    ...
    "body": "{\"vox\":{\"id\":10431,\"summary_text\":\"Vox received from 978-1913905101 via Book reviews at 17:17 (UTC) on 26/01/2022\",\"send_time\":\"2022-01-26T17:17:51.812Z\",\"contact_email\":\"\",\"contact_phone\":\"\",\"channel_name\":\"Book reviews\",\"channel_public_name\":\"telbee\",\"duration\":1,\"vox_context\":null,\"channel_id\":2786,\"recording_url\":\"https://api.telbee.io/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBczh6IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--9fdab42822e2a9235f03ca178ae917a83941b6cd/Wed%20Jan%2026%202022%2019-17-51%20GMT+0200%20(Eastern%20European%20Standard%20Time)\",\"direction\":\"vox_in\",\"channel_status\":\"active\",\"transcription_state\":\"not_transcribed\",\"share_link\":\"https://app.telbee.io/vox/Djw3em5mEMse6yjM5aA4S6oM\",\"vox_no\":2,\"sending_user\":null,\"contact_name\":\"978-1913905101\",\"contact_id\":6275,\"actual_transcription\":\"\",\"transcription_language\":\"en-US\",\"conversation_inbox_url\":\"https://app.telbee.io/inbox?token=iP9jHf2KVVrZuZRoe7n9NFLT\",\"sending_user_id\":null}}",
    "isBase64Encoded": false
}

But when I try to get the vox element of the body it fails但是当我尝试获取身体的vox元素时它失败了

console.log('event body = ' + JSON.parse(event.body.vox.contact_name));

The error message is错误信息是

{
    "errorType": "TypeError",
    "errorMessage": "Cannot read property 'contact_name' of undefined",
    "stack": [
        "TypeError: Cannot read property 'contact_name' of undefined",
        "    at Runtime.exports.handler (/var/task/index.js:49:69)",
        "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
    ]
}

I'm not sure how to get access to event.body.vox.contact_name even though I know it's there in the payload I cant get access to it.我不确定如何访问event.body.vox.contact_name ,即使我知道它在我无法访问的有效负载中。 I know I have to parse it first as it is escaped but the console.log does not allow me to access the event objects body element.我知道我必须先解析它,因为它被转义了,但是 console.log 不允许我访问事件对象 body 元素。 I'm not sure what the issue could be as this is the event payload that is passed into this lambda function that I am creating and is attached to an AWS Gateway.我不确定问题可能是什么,因为这是传递到我正在创建并附加到 AWS 网关的 lambda function 的事件负载。

You are trying to get a value before parsing.Try this您试图在解析之前获取一个值。试试这个

var body=JSON.parse(event.body);
var contactName=body.vox.contact_name; // 978-1913905101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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