How to express JSON as a string in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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!

3rd Feb 2019, 11:43 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
10 Answers
+ 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!
4th Feb 2019, 12:29 PM
Benneth Yankey
Benneth Yankey - avatar
+ 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!
4th Feb 2019, 1:22 AM
Benneth Yankey
Benneth Yankey - avatar
+ 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
4th Feb 2019, 9:08 AM
Benneth Yankey
Benneth Yankey - avatar
+ 3
⏩ Prometheus ⏪ please could you share the code snippet, so we help to solve the problem. Because it should work. Thanks
4th Feb 2019, 6:30 AM
Benneth Yankey
Benneth Yankey - avatar
+ 3
https://code.sololearn.com/WTVWLi13YRRW/?ref=app Ben Bright I'm doing this for purely debugging purposes only
4th Feb 2019, 7:10 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 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.
4th Feb 2019, 3:34 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
JSON.stringify(data)
4th Feb 2019, 3:58 AM
Random
Random - avatar
4th Feb 2019, 12:33 PM
Benneth Yankey
Benneth Yankey - avatar
+ 1
Thanks Ben Bright! Could you mind explaining the null and 2 parameters? Thanks!
4th Feb 2019, 12:31 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar