代码之家  ›  专栏  ›  技术社区  ›  John

如何从JSON中提取值

  •  0
  • John  · 技术社区  · 7 年前

    使用节点。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 jsonBody = JSON.parse(body);
                var valueReturned = jsonBody["response"];
                console.log("logs: " + valueReturned);
    // returns: logs: undefined
    

    有人知道我错在哪里吗?

    谢谢你

    3 回复  |  直到 7 年前
        1
  •  2
  •   Sam Ho    7 年前

    您需要一个有效的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);
        2
  •  0
  •   limbuster    7 年前

    问题是 身体 不是有效的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
        3
  •  0
  •   CertainPerformance    7 年前

    如果你必须处理你的 body 将其手动转换为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);