Serializing to JSON in JavaScript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
MarPlo
Posts:186

Serializing to JSON in JavaScript

I need to serialize an object to JSON in JavaScript. Is there a "standard" way to do this?
I have an array defined something like this:

Code: Select all

var countries = [];
countries[0] = 'ga';
countries[1] = 'cd';
...
And I need to convert this into a json string to pass to $.ajax() like this:

Code: Select all

$.ajax({
  type: "POST",
  url: "Concessions.aspx/GetConcessions",
  data: "{'countries': ['ga','cd']}",
...

Admin Posts:805
Use the JSON object methods.
- To convert an object to a string, use JSON.stringify():

Code: Select all

var json_string = JSON.stringify(your_object, null, 2);
- To convert a JSON string to object, use JSON.parse():

Code: Select all

var your_object = JSON.parse(json_string);

Similar Topics