Convert JS object to JSON string
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
Bin Chen
Updated on July 08, 2022Comments
-
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 almost 8 years
JSON.stringify()
is the method you're looking for. -
Egan Wolf about 6 yearsThere's always that first time when you have to learn it.
-
Justin Meskan almost 4 yearsJSON.stringify is also a good way to copy an object
-
-
AabinGunz almost 13 yearsdownload this script in order for
JSON.stringify(j);
to work -
georgelviv about 9 yearsWork on nodejs because node use same engine
-
Andris over 8 yearsThis 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 over 8 yearsdoes not escape strings with quotation marks like: "a \" in a string"
-
Glenn Lawrence almost 8 yearsFor a bit more clarity:
replacer
is optional, so if you want to still use thespace
arg you putnull
forreplacer
. 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 about 7 yearsThanks for adding the reverse process.
-
Ritesh almost 7 yearsJSON.stringify doesn't convert nested objects. Any solution for that..??
-
Fanky almost 7 yearsto be precise
j=JSON.stringify(j);
orvar newvar=JSON.stringify(j);
-
Jacek Gzel over 6 yearsIf You need more readable json string You can use space parameter like
var formattedJSON = JSON.stringify(j, null, 2);
-
Manuel Romeiro over 6 yearsThat 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 over 4 yearsYou 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 about 4 yearsReferences 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 almost 4 yearsofcourse this code is just an example of playing with codes .. we should always use stringify ... JS had done the job already for us