我需要将一个对象序列化为JSON。我用的是jQuery。是否有一个“标准”的方法来做到这一点?

我的具体情况:我有一个数组定义如下所示:

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

我需要把它变成一个字符串传递给$.ajax()像这样:

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

当前回答

基本上分为两步:

首先,你需要像这样进行字符串化:

var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2); 

之后,你需要将字符串转换为Object:

var obj = JSON.parse(JSON_VAR);

其他回答

最好的方法是包含JSON对象的填充。

但是如果你坚持在jQuery命名空间中创建一个方法来将对象序列化为JSON符号(JSON的有效值),你可以这样做:

实现

// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function ($) {
  var _PRIMITIVE, _OPEN, _CLOSE;
  if (window.JSON && typeof JSON.stringify === "function")
    return JSON.stringify;

  _PRIMITIVE = /string|number|boolean|null/;

  _OPEN = {
    object: "{",
    array: "["
  };

  _CLOSE = {
    object: "}",
    array: "]"
  };

  //actions to execute in each iteration
  function action(key, value) {
    var type = $.type(value),
      prop = "";

    //key is not an array index
    if (typeof key !== "number") {
      prop = '"' + key + '":';
    }
    if (type === "string") {
      prop += '"' + value + '"';
    } else if (_PRIMITIVE.test(type)) {
      prop += value;
    } else if (type === "array" || type === "object") {
      prop += toJson(value, type);
    } else return;
    this.push(prop);
  }

  //iterates over an object or array
  function each(obj, callback, thisArg) {
    for (var key in obj) {
      if (obj instanceof Array) key = +key;
      callback.call(thisArg, key, obj[key]);
    }
  }

  //generates the json
  function toJson(obj, type) {
    var items = [];
    each(obj, action, items);
    return _OPEN[type] + items.join(",") + _CLOSE[type];
  }

  //exported function that generates the json
  return function stringify(obj) {
    if (!arguments.length) return "";
    var type = $.type(obj);
    if (_PRIMITIVE.test(type))
      return (obj === null ? type : obj.toString());
    //obj is array or object
    return toJson(obj, type);
  }
}(jQuery));

使用

var myObject = {
    "0": null,
    "total-items": 10,
    "undefined-prop": void(0),
    sorted: true,
    images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
    position: { //nested object literal
        "x": 40,
        "y": 300,
        offset: [{ top: 23 }]
    },
    onChange: function() { return !0 },
    pattern: /^bg-.+\.(?:png|jpe?g)$/i
};

var json = jQuery.stringify(myObject);
console.log(json);

我已经使用jquery-json 6个月了,它工作得很好。使用起来非常简单:

var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);

// Result: {"foo":"bar","baz":"wockaflockafliz"}

我确实在某个地方找到了这个。但不记得在哪里了……可能在StackOverflow:)

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

基本上分为两步:

首先,你需要像这样进行字符串化:

var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2); 

之后,你需要将字符串转换为Object:

var obj = JSON.parse(JSON_VAR);

是的,您应该使用JSON。stringify和JSON。在调用$.ajax之前解析Json_PostData:

$.ajax({
        url:    post_http_site,  
        type: "POST",         
        data:   JSON.parse(JSON.stringify(Json_PostData)),       
        cache: false,
        error: function (xhr, ajaxOptions, thrownError) {
            alert(" write json item, Ajax error! " + xhr.status + " error =" + thrownError + " xhr.responseText = " + xhr.responseText );    
        },
        success: function (data) {
            alert("write json item, Ajax  OK");

        } 
});