Reputation: 3945
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
Upvotes: 0
Views: 84
Reputation: 370619
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);
Upvotes: 0
Reputation: 81
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
Upvotes: 0
Reputation: 206
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);
Upvotes: 2