简体   繁体   English

如何使用javascript获取内部对象文字值

[英]How to get an inner object literal value with javascript

After calling console.log(JSON.stringify(req.params)) , I get a string with the following structure: 调用console.log(JSON.stringify(req.params)) ,我得到一个具有以下结构的字符串:

{"q":"{\"email\":\"mymail@mail.com\"}","apiKey":"1234"}

With console.log(req.params.q) , I have this result: {"email":"mymail@mail.com"} . 使用console.log(req.params.q) ,我得到以下结果: {"email":"mymail@mail.com"} But I get "undefined" if I try to view the email value with console.log(req.params.q.email) or console.log(req.params.q["email"]) What is the best approach to get that value? 但是,如果我尝试使用console.log(req.params.q.email)console.log(req.params.q["email"])查看电子邮件值,则会得到“未定义”的信息那个值?

You must JSON.parse that inner part : 您必须JSON.parse该内部部分:

var test = {"q":"{\"email\":\"mymail@mail.com\"}","apiKey":"1234"};
alert(JSON.parse(test.q).email);

alerts mymail@mail.com 警报mymail@mail.com

Why? 为什么?

Because test holds an javascript object where q holds a string, So you must parse that string if you want to extract the JSON values from that string. 由于test包含一个JavaScript对象,其中q包含一个字符串,因此,如果要从该字符串中提取JSON值,则必须解析该字符串。

It looks like req.params.q is a string: "{\\"email\\":\\"mymail@mail.com\\"}" . 看起来req.params.q是一个字符串: "{\\"email\\":\\"mymail@mail.com\\"}"

You need to parse that json then fetch the value. 您需要解析该json,然后获取值。

req = {params: {"q":"{\"email\":\"mymail@mail.com\"}","apiKey":"1234"}}
JSON.parse(req.params.q)
> Object {email: "mymail@mail.com"}
JSON.parse(req.params.q).email
> "mymail@mail.com"

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

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