I have seen several posts about json2.js and the stringify method it provides. However, the posts I have seen are from almost a year ago. Is there a better library to use today or does jQuery directly support stringify functionality?
2 Answers
The JSON object has been defined in ECMAScript 5th ed, and is already available in most modern browsers. No special setup is needed. Calling,
JSON.stringify(someObject)
will spit out a JSON representation of the passed in object. If you want compatibility for older browsers, then simply include Crocford's json2.js on your page. json2.js will use the browser's native implementation, if available.
Comments
You can use the .serialize() method on a form to give you a JSON string of a jQuery form object. It's usually what I use if I'm doing an AJAX POST request.
Example:
<form id="SomeForm">
<input name="hello" type="hidden" value="world" />
</form>
<script>
$('#SomeForm').serialize(); // '{ "hello": "world" }'
</script>
3 Comments
John Livermore
Ok, thanks. So this will serialize to json elements in a form. What if I have a js object? Is there another method (save from writing your own) besides json2.js?
Anurag
Doesn't
serialize give URL encoded parameters instead of JSON?John Livermore
@Anurag - you are correct. after closer examination it produces a formatted querystring, not json