【问题标题】:Accessing values in JSON object访问 JSON 对象中的值
【发布时间】:2018-02-10 16:07:57
【问题描述】:

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

【问题讨论】:

  • 您确定event.body 确实包含该值吗?因为event.body.article_url 应该可以工作。
  • @GrégoryNEUT 是的,我很确定,因为我在event.body 上做了一个console.log,它显示其中的内容{"article_url": "http://technewstt.com/bd1108/"}
  • console.log(typeof event.body)console.log(Object.keys(event.body)) 怎么样
  • 所以试试JSON.parse(event.body).article_url
  • @GrégoryNEUT JSON.parse(event.body).article_url 工作谢谢

标签: javascript json node.js object


【解决方案1】:

如果你确定event.body包含正确的数据,你可以用json解析得到valuekey

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
【解决方案2】:

最好的方法:

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

【讨论】:

    【解决方案3】:

    使用body-parser中间件:

    const bodyParser = require('body-parser');
    
    app.use(bodyParser.json());
    

    那么,你应该没事。

    【讨论】:

    • 如果 OP 使用 connect 包,这间接是一个有效的建议。
    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    相关资源
    最近更新 更多