Convert JS object to JSON string

后端 未结 27 2536
庸人自扰
庸人自扰 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: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

提交回复
热议问题