1

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 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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?
Doesn't serialize give URL encoded parameters instead of JSON?
@Anurag - you are correct. after closer examination it produces a formatted querystring, not json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.