Convert JS object to JSON string

后端 未结 27 2491
庸人自扰
庸人自扰 2020-11-22 00:43

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:

相关标签:
27条回答
  • 2020-11-22 01:48

    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"}

    0 讨论(0)
  • 2020-11-22 01:49

    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.

    0 讨论(0)
  • 2020-11-22 01:49

    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

    0 讨论(0)
提交回复
热议问题