简体   繁体   中英

How to extract value from JSON

Using node.js 6.10

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

I want to extract the Not latest version of file, update not performed and place it into the valueReturned var. I have tried

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

does anyone know where I am going wrong?

ThankYous

You need a valid JSON string to parse 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); 

The problem is body is not a valid JSON format. The key and value should be wrapped in a double quotes("). Otherwise the code should work as shown below:

 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 

A hacky and unreliable method if you have to deal with your body as is would be to manually transform it into JSON format and then parse it:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM