简体   繁体   中英

I need to serialize an object to JSON. I'm using jQuery. Is there a “standard” way to do this?

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

My specific situation: I have an array defined as shown below:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...

and I need to turn this into a string to pass to $.ajax() like this:

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

You can use JSON.stringify(countries);

var c = {
   countries: countries
}
$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: JSON.stringify(c),
    contentType: "application/json"
...

Note that you will want to specify contentType ; otherwise, URI-encoding is assumed.

You can use JSON.stringify() to turn any object in to a JSON string:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'

// or more simply:
var countries = [ 'ga', 'cd' ];
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'

However, you should note that it's better practice to provide the data property of $.ajax with an object as jQuery will then create the JSON for you and at the same time escape any invalid characters and do any required encoding. Try this:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: {
        'countries': countries
    }
});

you can use JSON.parse() to convert object to json

like this countries = JSON.parse(countries);

object is convert in json and store in countries variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM