访问JSON对象中的值

4

我有一个JSON对象event.body,其中包含{"article_url": "http://technewstt.com/bd1108/"},我如何访问article_url的值,换句话说,我想使用字符串http://technewstt.com/bd1108/
我尝试了event.body.article_urlevent.article_url,它们都是undefined


1
你确定 event.body 包含了那个值吗?因为 event.body.article_url 应该是有效的。 - Orelsanpls
@GrégoryNEUT 是的,我确定,因为我在event.body上执行了console.log,它显示其中包含内容{"article_url": "http://technewstt.com/bd1108/"} - Kern Elliott
1
console.log(typeof event.body)console.log(Object.keys(event.body)) 怎么样? - Orelsanpls
console.log(typeof event.body) 返回 string,而 console.log(Object.keys(event.body)) 返回数字 0 到 47。 - Kern Elliott
2
所以请尝试使用 JSON.parse(event.body).article_url - Orelsanpls
1
@GrégoryNEUT JSON.parse(event.body).article_url 已经生效,谢谢。 - Kern Elliott
3个回答

0

如果您确定event.body包含正确的数据,您可以使用JSON解析它并获取

JSON.parse('{"article_url": "http://technewstt.com/bd1108/"}', (key, value) => {
  console.log(key);  //logs the key which is article_url
  return value;      // returns the url value
})

这相当于

JSON.parse(JSON.stringify(event.body), (key, value) => {
  console.log(key);  
  return value;      
})

其他选项,例如用户@Grégory NEUT的评论将返回URL值

JSON.parse(event.body).article_url  //returns the url value

我需要的值是通过尝试 JSON.parse(event.body).article_url 返回的,也要感谢这个方法。 - Kern Elliott

0

最佳实践:

var url = JSON.parse(event.body).article_url;

-1
使用 body-parser 中间件:
const bodyParser = require('body-parser');

app.use(bodyParser.json());

那么,你应该没问题了。


这是一种间接有效的建议,假设 OP 使用了 connect 包。 - Ram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接