+ 5
How to express JSON as a string in JavaScript
I need help with this. No matter which way I use to convert it to a string, the output is always [object Object]. How can I get the actual content of the JSON object? Thanks!
10 Respuestas
+ 3
⏩ Prometheus ⏪ ok so I didn't really check the type of json the api returns. It turns out to be an array json which contains one big object.
=> solution
```
if(window.fetch){
//code here
})
.then(function(myJson) {
// select the object first from
// json data
let output = myJson[0]; <-- this was the problem.
// here output is a normal
// object, so you could access
// all properties such
output.name
// stringify whole object to
// document body
document.write(JSON.stringify(output, null, 2));
```
Hope it helps, happy coding!
+ 6
convert your JSON data to actual javascript object as follows:
var output = JSON.parse(data);
console.log(output);
you now can do whatever u want with the object.
Hope it helps, happy coding!
+ 5
⏩ Prometheus ⏪ so I did little debugging and error handling with:
```function handleResponse(response) {
let contentType = response.headers.get("content-type");
if (contentType.includes("application/json")) {
return function(response) {
if (response.ok) {
return response.json()
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText
})
}
}
} else if (contentType.includes("text/html")) {
return function(response) {
if (response.ok) {
return response.text()
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText
})
}
}
}
}
```
and the json still can't be parsed into actual object. please run code in actual browser and let's see. Thanks
+ 3
⏩ Prometheus ⏪ please could you share the code snippet, so we help to solve the problem. Because it should work. Thanks
+ 3
https://code.sololearn.com/WTVWLi13YRRW/?ref=app
Ben Bright
I'm doing this for purely debugging purposes only
+ 2
Thank you Ben Bright!
But I have tried your approach and I get an error, saying "JSON" is not recognized or smthing like that.
+ 2
JSON.stringify(data)
+ 2
⏩ Prometheus ⏪ please read from here:
https://javascript.info/json
+ 1
Thanks Ben Bright!
Could you mind explaining the null and 2 parameters? Thanks!