Convert JS object to JSON string


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:

9/18/2018 9:33:34 AM

Accepted Answer

All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:

var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'
4/15/2017 7:08:37 PM

With JSON.stringify() found in json2.js or native in most modern browsers.

   JSON.stringify(value, replacer, space)
        value       any JavaScript value, usually an object or array.

       replacer    an optional parameter that determines how object
                    values are stringified for objects. It can be a
                    function or an array of strings.

       space       an optional parameter that specifies the indentation
                    of nested structures. If it is omitted, the text will
                    be packed without extra whitespace. If it is a number,
                    it will specify the number of spaces to indent at each
                    level. If it is a string (such as '\t' or ' '),
                    it contains the characters used to indent at each level.

       This method produces a JSON text from a JavaScript value.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow