首页 文章

在jQuery中序列化为JSON [重复]

提问于
浏览
1160

这个问题在这里已有答案:

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

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

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

我需要将其转换为字符串以传递给 $.ajax() ,如下所示:

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

11 回答

  • 1103

    如果您不想使用外部库,则有 .toSource() 本机JavaScript方法,但它不是完全跨浏览器的 .

  • 94

    我已经使用了jquery-json 6个月了,效果很好 . 它使用起来非常简单:

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

    我没用过它,但你可能想试试 jQuery plugin written by Mark Gibson

    它添加了两个函数: $.toJSON(value)$.parseJSON(json_str, [safe]) .

  • 44

    这基本上是两步过程:

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

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

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

    var obj = JSON.parse(JSON_VAR);
    
  • 35

    我确实找到了这个地方 . 不记得在哪里...可能在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;
    };
    
  • 10

    最好的方法是包含JSON对象的polyfill .

    但是如果你坚持在jQuery命名空间内创建一个将对象序列化为JSON表示法(valid values for 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);
    
  • 182

    是的,在调用$ .ajax之前,你应该JSON.stringify和JSON.parse你的“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");
    
            } 
    });
    
  • 8

    JSON-js - JavaScript中的JSON .

    要将对象转换为字符串,请使用 JSON.stringify

    var json_text = JSON.stringify(your_object, null, 2);
    

    要将JSON字符串转换为对象,请使用 JSON.parse

    var your_object = JSON.parse(json_text);
    

    最近由John Resig推荐:

    ...请开始将使用JSON的应用程序迁移到Crockford的json2.js . 它与ECMAScript 5规范完全兼容,如果存在本机(更快!)实现,则会优雅地降级 . 事实上,我刚刚在jQuery中进行了一次更改,它使用了JSON.parse方法,如果它存在,现在已经完全指定了 .

    我倾向于相信他在JavaScript问题上所说的话:)

    Newer browsers本地支持JSON object . Crockford的JSON库的当前版本将仅定义 JSON.stringifyJSON.parse ,如果它们尚未定义,则保留任何浏览器本机实现 .

  • 8

    不,序列化为JSON的标准方法是使用现有的JSON序列化库 . 如果您不希望这样做,那么您将不得不编写自己的序列化方法 .

    如果您需要有关如何执行此操作的指导,我建议您检查一些可用库的来源 .

    EDIT: 对于您的应用程序来说,使用格式正确的JSON非常重要,那么您必须权衡"one more dependency"的开销与您的自定义方法有一天可能遇到您未曾预料到的故障情况的可能性 . 您的电话是否可以接受这种风险 .

  • 11

    Works on IE8+

    不需要jQuery,使用:

    JSON.stringify(countries);
    
  • 27

    上述解决方案没有考虑的一件事是,如果您有一个输入数组但只提供了一个值 .

    例如,如果后端需要一组People,但在这种特殊情况下,您只需要处理一个人 . 然后做:

    <input type="hidden" name="People" value="Joe" />
    

    然后使用之前的解决方案,它只会映射到以下内容:

    {
        "People" : "Joe"
    }
    

    但它应该真正映射到

    {
        "People" : [ "Joe" ]
    }
    

    要解决此问题,输入应如下所示:

    <input type="hidden" name="People[]" value="Joe" />
    

    你会使用以下功能(基于其他解决方案,但扩展了一点)

    $.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (this.name.substr(-2) == "[]"){
            this.name = this.name.substr(0, this.name.length - 2);
            o[this.name] = [];
        }
    
        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;
    };
    

相关问题