Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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"}'
share|improve this question
4  
JSON.stringify() is the method you're looking for. – Gowtham G Jun 24 at 5:33

17 Answers 17

up vote 1005 down vote accepted

Modern browsers (IE8, FF3, Chrome etc.) have native JSON support built in (Same API as with JSON2).

So as long you're not dealing with IE6/7 you can do it just as easily as that:

var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'

But to add support for the oldie's, you should also include the json2 script

share|improve this answer
4  
download this script in order for JSON.stringify(j); to work – abi1964 Jul 21 '11 at 9:55
4  
Working also on nodejs!!! – Frederic Yesid Peña Sánchez Feb 19 '15 at 17:54
    
Work on nodejs because node use same engine – georgelviv May 3 '15 at 20:33
1  
IE8 should be a really modern browser ;) – Serge Sep 11 '15 at 12:57
11  
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. – Andris Sep 11 '15 at 13:52

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.
share|improve this answer
3  
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 – Glenn Lawrence Jul 29 at 8:22

Check out updated/better way:

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.
share|improve this answer

Json Stringify can convert your js object to json

 var x = {"name" : "name1"};
 JSON.stringify(x);
share|improve this answer
JSON.stringify({"key":"value"});
share|improve this answer

If you're using AngularJS, the 'json' filter should do it:

<span>{{someObject | json}}</span>
share|improve this answer

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.

share|improve this answer

In angularJS

angular.toJson(obj, pretty);

obj: Input to be serialized into JSON.

pretty(optional):
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

(default: 2)

share|improve this answer

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

share|improve this answer

One custom defined for this , until we do strange from stringify method

var j={"name":"binchen","class":"awesome"};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j)
{
json += dq+x+dq+":"+dq+j[x]+dq;
count++;
if(count<last)
   json +=",";
}
json+="}";
document.write(json);

OUTPUT

{"name":"binchen","class":"awesome"}

LIVE http://jsfiddle.net/mailmerohit5/y78zum6v/

share|improve this answer
    
does not escape strings with quotation marks like: "a \" in a string" – antmary Jan 19 at 8:14
var someObj = { "name" : "some name" };
var someObjStr = JSON.stringify(someObj);
console.log( someObjStr  );
share|improve this answer

you can use native stringify function like this

const j={ "name": "binchen" }

/** convert json to string */
const jsonString = JSON.stringify(j)

console.log(jsonString) // {"name":"binchen"}

share|improve this answer

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

share|improve this answer

Woking... Easy to use

$("form").submit(function(evt){
  evt.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvert = JSON.stringify(formData);  // Convert to json
});

Thanks

share|improve this answer

Just Copy and pase

$("form").submit(function(evt){
  evt.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
});
share|improve this answer

if you want to get json properties value in string format use the following way

var i = {"x":1}

var j = JSON.stringify(i.x);

var k = JSON.stringify(i);

console.log(j);

"1"

console.log(k);

'{"x":1}'
share|improve this answer

if you have a json string and it's not wrapped with [] then wrap it up first

var str = '{"city": "Tampa", "state": "Florida"}, {"city": "Charlotte", "state": "North Carolina"}';
str = '[' + str + ']';
var jsonobj = $.parseJSON(str);

OR

var jsonobj = eval('(' + str + ')');
console.log(jsonobj);
share|improve this answer
    
The OP is trying to go the other way. Your question answers the reverse case where he has a JSON string and wants to get it as an object. – Joshua Snider Jun 15 '15 at 2:50
    
you have done reverse thing to question.. you should use JSON.stringfy() function – Hardik Patel Jan 29 at 10:01

protected by Community Aug 24 at 7:32

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.