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

本文翻译自:Serializing to JSON in jQuery [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

I need to serialize an object to JSON . 我需要将对象序列化为 JSON I'm using jQuery . 我正在使用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()如下所示:

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

#1楼

参考:https://stackoom.com/question/nur/在jQuery中序列化为JSON-重复


#2楼

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


#3楼

I haven't used it but you might want to try the jQuery plugin written by Mark Gibson 我没有使用它,但你可能想尝试由Mark Gibson编写jQuery插件

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


#4楼

No, the standard way to serialize to JSON is to use an existing JSON serialization library. 不,序列化为JSON的标准方法是使用现有的JSON序列化库。 If you don't wish to do this, then you're going to have to write your own serialization methods. 如果您不希望这样做,那么您将不得不编写自己的序列化方法。

If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries. 如果您需要有关如何执行此操作的指导,我建议您检查一些可用库的来源。

EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. 编辑:我不打算说出你自己的serliazation方法是坏的,但你必须考虑如果你的应用程序使用格式良好的JSON很重要,那么你必须权衡“一个依赖“反对你的自定义方法可能有一天遇到你没有预料到的失败案例的可能性。 Whether that risk is acceptable is your call. 您的电话是否可以接受这种风险。


#5楼

One thing that the above solutions don't take into account is if you have an array of inputs but only one value was supplied. 上述解决方案没有考虑的一件事是,如果您有一个输入数组,但只提供了一个值。

For instance, if the back end expects an array of People, but in this particular case, you are just dealing with a single person. 例如,如果后端需要一组People,但在这种特殊情况下,您只需要处理一个人。 Then doing: 然后做:

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

Then with the previous solutions, it would just map to something like: 然后使用以前的解决方案,它只会映射到以下内容:

{
    "People" : "Joe"
}

But it should really map to 但它应该真正映射到

{
    "People" : [ "Joe" ]
}

To fix that, the input should look like: 要解决此问题,输入应如下所示:

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

And you would use the following function (based off of other solutions, but extended a bit) 你会使用以下功能(基于其他解决方案,但扩展了一点)

$.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;
};

#6楼

The best way is to include the polyfill for JSON object. 最好的方法是将polyfill包含在JSON对象中。

But if you insist create a method for serializing an object to JSON notation ( valid values for JSON ) inside the jQuery namespace, you can do something like this: 但是如果你坚持在jQuery命名空间内创建一个将对象序列化为JSON表示法(JSON的有效值 )的方法,你可以这样做:

Implementation 履行

// 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));

Usage 用法

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);
发布了0 篇原创文章 · 获赞 136 · 访问量 83万+

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/105266575