Reputation: 153
I am logging a response
that I get from the server after sending a post request, and it looks like this:
{"output":"basic question #1. how do I calculate the area of a rectangle based on users input in python?"}
now i want to access output
as type plain text (string). I tried this:
console.log(body)
//this returns {"output":"basic question #1. how do I calculate the area of a rectangle based on users input in python?"}
console.log(JSON.stringify(body))
//this returns "{\"output\":\"calculate the area of a rectangle based on users input in python\"}"
how would I access output
within the body
response?
Upvotes: 0
Views: 31
Reputation: 3748
There is a built-in method called JSON.parse()
in JavaScript that will convert JSON to a JavaScript object.
Follow these steps to get the result you want!
Skip if already parsed! First, you need to use JSON.parse()
to parse the string
JSON into a valid JavaScript object. As a parameter, you pass in the string that you want to parse.
JSON.parse(body);
To access the body, you can either use dot notation or bracket notation. Either one will work; you use them like below.
// Dot notation
body.output;
// Bracket notation
body["output"];
The final code should look like this.
const body = `{"output": "Calculate the area of a rectangle based on users input in Python."}`;
const parsed = JSON.parse(body);
// Dot notation
console.log(parsed.output);
// Bracket notation
console.log(parsed["output"]);
In conclusion, the JSON.parse()
method built-into JavaScript should help solve the issue.
Upvotes: 1