如何从JSON中提取值

时间:2018-05-03 03:40:04

标签: javascript json node.js

使用node.js 6.10

console.log("returned data1 " + body);
// returns: returned data1 "{'response' : 'Not latest version of file, update not performed'}"

我想提取Not latest version of file, update not performed并将其放入valueReturned var。我试过了

    var jsonBody = JSON.parse(body);
            var valueReturned = jsonBody["response"];
            console.log("logs: " + valueReturned);
// returns: logs: undefined

有谁知道我哪里出错了?

ThankYous

3 个答案:

答案 0 :(得分:2)

您需要一个有效的JSON字符串来解析JSON。



let body = "{ \"response\" : \"Not latest version of file, update not performed\"}";
let jsonBody = JSON.parse(body);
let valueReturned = jsonBody.response;
console.log("logs: " + valueReturned);




答案 1 :(得分:0)

问题是 body 不是有效的JSON格式。键和值应该用双引号(“)括起来。否则代码应该如下所示:

const body = '{ "response" : "Not latest version of file, update not performed" }';

console.log("returned data1 " + body);
// returns: returned data1 "{'response' : 'Not latest version of file, update not performed'}"

var jsonBody = JSON.parse(body);
var valueReturned = jsonBody["response"];
console.log("logs: " + valueReturned);
// returns: logs: undefined

答案 2 :(得分:0)

如果你必须处理你的body,那么一种hacky和不可靠的方法就是手动将其转换为JSON格式然后解析它:



const body = `"{'response' : 'Not latest version of file, update not performed'}"`;
const formattedBody = body
  .slice(1, body.length - 1)
  .replace(/'/g, '"');
const obj = JSON.parse(formattedBody);
console.log(obj.response);