If I defined an object in JS with:
var j={\"name\":\"binchen\"};
How can I convert the object to JSON? The output string should be:
you can use native stringify function like this
const j={ "name": "binchen" }
/** convert json to string */
const jsonString = JSON.stringify(j)
console.log(jsonString) // {"name":"binchen"}
You can use JSON.stringify() method to convert JSON object to String.
var j={"name":"binchen"};
JSON.stringify(j)
For reverse process, you can use JSON.parse() method to convert JSON String to JSON Object.
I was having issues with stringify running out of memory and other solutions didnt seem to work (at least I couldn't get them to work) which is when I stumbled on this thread. Thanks to Rohit Kumar I just iterate through my very large JSON object to stop it from crashing
var j = MyObject;
var myObjectStringify = "{\"MyObject\":[";
var last = j.length
var count = 0;
for (x in j) {
MyObjectStringify += JSON.stringify(j[x]);
count++;
if (count < last)
MyObjectStringify += ",";
}
MyObjectStringify += "]}";
MyObjectStringify would give you your string representaion (just as mentioned other times in this thread) except if you have a large object, this should also work - just make sure you build it to fit your needs - I needed it to have a name than array