JSON 解析对象

JSON parse object

本文关键字:对象 JSON      更新时间:2023-09-26

我有以下来自HTTP请求的JSON字符串:

{ '{firstname:''Joe''}': '' } // output of console.log(req.body);

我尝试使用以下方法将值打印到控制台:

console.log(req.body.firstname);

但它说该值未定义。如何获取名字的值?

要查看客户端正在执行的操作,以下是它发送 JSON 请求的方式:

//angular2
headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.http.post(
            'http://192.168.1.45:3000/test', 
            JSON.stringify({firstname:'Joe'}), //This is the parameter I want
            {headers:headers}
        )
使用

JSON.stringify 将数组转换为 JSON 字符串,然后使用 JSON.parse 将该字符串转换回数组

<html>
    <head>
    <script>
    function gettz(){
     var str=JSON.stringify({firstname:'Joe'});
     console.log(str);
     //Parse an object 
     dataObj = JSON.parse(str);
    // get object property
      console.log(dataObj.firstname);
    }
    </script>
    </head>
     <body>
        <input type="button" id="button" value="PrintJson" onclick="gettz();">
     </body>
     </html>

当你收到它时,你需要先解析响应,因为它是一个字符串,所以:

var parsedResponse = JSON.parse(req.body);
console.log(parsedResponse.firstname); //Now you can access the object