Convert JS object to JSON string

1,692,698

Solution 1

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"
};
console.log(JSON.stringify(j));

Solution 2

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.

Solution 3

Check out updated/better way by Thomas Frank:

Update May 17, 2008: Small sanitizer added to the toObject-method. Now toObject() will not eval() the string if it finds any malicious code in it.For even more security: Don't set the includeFunctions flag to true.

Douglas Crockford, father of the JSON concept, wrote one of the first stringifiers for JavaScript. Later Steve Yen at Trim Path wrote a nice improved version which I have used for some time. It's my changes to Steve's version that I'd like to share with you. Basically they stemmed from my wish to make the stringifier:

  • handle and restore cyclical references
  • include the JavaScript code for functions/methods (as an option)
  • exclude object members from Object.prototype if needed.

Solution 4

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.

Solution 5

JSON.stringify(j, null, 4) would give you beautified JSON in case you need beautification also

The second parameter is replacer. It can be used as Filter where you can filter out certain key values when stringifying. If set to null it will return all key value pairs

Share:
1,692,698
Bin Chen
Author by

Bin Chen

Updated on July 08, 2022

Comments

  • Bin Chen
    Bin Chen almost 2 years

    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:

    '{"name":"binchen"}'
    
    • Gowtham
      Gowtham almost 8 years
      JSON.stringify() is the method you're looking for.
    • Egan Wolf
      Egan Wolf about 6 years
      There's always that first time when you have to learn it.
    • Justin Meskan
      Justin Meskan almost 4 years
      JSON.stringify is also a good way to copy an object
  • AabinGunz
    AabinGunz almost 13 years
    download this script in order for JSON.stringify(j); to work
  • georgelviv
    georgelviv about 9 years
    Work on nodejs because node use same engine
  • Andris
    Andris over 8 years
    This answer was posted a year before IE9 was released so at the time of writing IE8 was a modern browser indeed, or at least it was the newest IE available.
  • alphakevin
    alphakevin over 8 years
    does not escape strings with quotation marks like: "a \" in a string"
  • Glenn Lawrence
    Glenn Lawrence almost 8 years
    For a bit more clarity: replacer is optional, so if you want to still use the space arg you put null for replacer. If you are interested in using this function for pretty printing I found this answer to be also useful: stackoverflow.com/a/7220510/857209
  • David Lavieri
    David Lavieri about 7 years
    Thanks for adding the reverse process.
  • Ritesh
    Ritesh almost 7 years
    JSON.stringify doesn't convert nested objects. Any solution for that..??
  • Fanky
    Fanky almost 7 years
    to be precise j=JSON.stringify(j); or var newvar=JSON.stringify(j);
  • Jacek Gzel
    Jacek Gzel over 6 years
    If You need more readable json string You can use space parameter like var formattedJSON = JSON.stringify(j, null, 2);
  • Manuel Romeiro
    Manuel Romeiro over 6 years
    That custom code is very incomplete. Does not support arrays, objects and special chars. Example: the json {"arr":["1", "2", "3"],"obj":{"a":"b"},"key\"with\\special}chars":"value"} will output {"arr":"1,2,3","obj":"[object Object]","key"with\special}chars":"value"} that is wrong!
  • Mohammad Ghonchesefidi
    Mohammad Ghonchesefidi over 4 years
    You just saved my day. I was not able to save my object. the key that fields which have undefined value will not be included into json solved my problem!
  • yash
    yash about 4 years
    References of JSON parsing in JS: JSON.parse() : w3schools.com/js/js_json_parse.asp JSON.stringify() : w3schools.com/js/js_json_stringify.asp
  • Rohit Kumar
    Rohit Kumar almost 4 years
    ofcourse this code is just an example of playing with codes .. we should always use stringify ... JS had done the job already for us