9

I am using to a jQuery post method to send some data to a server. Rather than constructing the JSON string myself, I would like to simply use a JavaScript object. When I get the return string (in JSON) I would like to automatically construct a corresponding JavaScript object.

Is this possible?

4 Answers 4

30

Checkout JSON.stringify() and JSON.parse() in JSON2 documentation

Example:

myData = JSON.parse(text); // from json string to js object

var myJSONText = JSON.stringify(myObject, replacer); // js object to json string
Sign up to request clarification or add additional context in comments.

Comments

8

Yes.

If the JSON object is available, you can use :

var aString = JSON.stringify(anObject);

to transform an object into JSON string.

You can also convert a string into an object with

var obj = JSON.parse(aString)

To be sure that JSON is available, you can include this file https://github.com/douglascrockford/JSON-js

Comments

3

you should use Douglas Crockford's JSON2 library.

That way, you could:

var jsonString = JSON.stringify(obj);

or

var Obj = JSON.parse(jsonString);

1 Comment

You can do that anyway in modern browsers. JSON2 is a polyfill (worth using though)
0

If you use jQuery.getJSON you don't have to care about stringifying and parsing json, jquery does it for you.

2 Comments

Good thing to know, indeed. Same if you use $.ajax with "json" as dataType.
@CronosS, yep. getJSON is just a shorthand for $.ajax with "json" as dataType.

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.