javascript - Convert JS object to JSON string

ID : 916

viewed : 143

Tags : javascriptjsonstringobjectjavascript

Top 5 Answer for javascript - Convert JS object to JSON string

vote vote

95

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));

vote vote

87

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. 
vote vote

79

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.
vote vote

61

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.

vote vote

54

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

Top 3 video Explaining javascript - Convert JS object to JSON string

Related QUESTION?