Convert a JavaScript object to JSON

A colleague of mine was recently searching for a plug-in or script that can convert a JavaScript array to JSON. I asked him to check out JSON.stringify() in the json2.js library, which serializes the JavaScript object into JSON text. Here’s a sample if you do not know about this library:

Note: Make sure that you minify this library and then use the .js directly from your application. For demo purposes I am referring to this .js file directly. In production applications, it is not advisable to do so.

<script type="text/javascript" src="http://www.json.org/json2.js">
</
script>
<
script type="text/javascript">
var
arrCars = new Array("Toyota", "Mercedes", "BMW");
var jsonStr = JSON.stringify(arrCars);
alert(jsonStr);
</script>
JavaScript to JSON




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

10 comments:

Test said...

As a note, JSON.parse is native in modern browsers & json2.js is helpful for older browsers.

You can see @cowboy's blog post for more details http://j.mp/d2d2g9

~/Elijah Manor

Suprotim Agarwal said...

Yep! Thanks for adding that comment Elijah. Here's some more info:
http://ejohn.org/blog/the-state-of-json/

Anonymous said...

What is means of curry. i thing it is a vegetable करी पत्ता

Suprotim Agarwal said...

Curry is a spice mixture of widely varying compositions. My site is called devcurry since it is a mixture of ideas, experiments and thoughts for developers to cook ;)

amrish said...

This is a very good site it contains information for both all kind of users.

Fuzzy said...

the returned string isnt json...

CoursesWeb said...

Hi,
The link to get the json2.js file seems not work, the page: json.org/json2.js returns 404 error. But it can be downloaded from:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
In modern browsers, the JSON.stringify() works without json2.js .

Anonymous said...

very helpful post.

kapil goutam said...

very helpful

Unknown said...

This is to good, thanks for sharing your knowledge with us. Following links also helped me and develpers.

http://msdn.microsoft.com/en-us/library/bb299886.aspx

http://www.mindstick.com/Articles/af150297-b1e0-4316-958e-5a0b11a4a016/?JavaScript%20Object%20Notation%20JSON%20in%20JavaScript%20and%20Net