In jQuery sequence into the JSON [repeat]

This translation from: Serializing to JSON in jQuery [Duplicate]

This question already has an answer here: The problem here has the answer:

Need to the I the serialize AN Object to JSON . I need an object is serialized to JSON . 'M a using the I jQuery . I am using jQuery . Is there a "standard" way to do this? Is there a "standard" way to do this?

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

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

Turn the this need to the I and INTO A String to Pass to $.ajax()like the this: I need to convert it to a string to be passed to $.ajax()the following:

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

#1st Floor

Reference: https://stackoom.com/question/nur/ in jQuery repeating sequence into JSON-


#2nd Floor

If you do not want to use an external library, there is .toSource()native JavaScript methods, but it is not fully cross-browser.


#3rd floor

But IT Used not have have the I Might you want to the try at The jQuery plugin written by Mark Gibson I did not use it, but you might want to try written by Mark Gibson 's jQuery plugin

Functions at The ADDS TWO IT: $.toJSON(value), $.parseJSON(json_str, [safe]). It adds two $.toJSON(value)functions: $.parseJSON(json_str, [safe]), .


#4th floor

No, the standard way to serialize to JSON is to use an existing JSON serialization library. No, serialized as JSON standard method is to use an existing JSON serialization library. If you do not wish to do this , then you're going to have to write your own serialization methods. If you do not wish to do so, you will 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. If you need instructions on how to do this, I suggest you check the source of some of the available libraries.

EDIT: the I'm not going to Come OUT and say that Writing your own serliazation Methods IS Bad, But you the MUST the Consider that IF IT's Important to your the Application to use Well-Formed JSON, the then you have have to Weigh at The overhead of "One More dependency "against the possibility that your custom methods may one day encounter a failure case that you had not anticipated. edit: I'm not going to tell your own serliazation method is bad, but you must consider if your application uses the format good JSON is important, then you have to weigh "a dependency" against your custom methods may one day encounter that you did not anticipate the possibility of failures. Whether that risk is acceptable is your call . Your phone can accept this risk.


#5th Floor

One thing that the above solutions do not take into account is if you have an array of inputs but only one value was supplied. Above solutions do not consider one thing, if you have an input array, but provides only a value.

For instance, if the back end expects an array of People, but in this particular case, you are just dealing with a single person. For example, if the backend requires a set of People, but in this particular case, you only need to deal with A person. Then doing: Then do:

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

Then with the previous solutions, it would just map to something like: Then use the previous solution, it will only be mapped to the following:

{
    "People" : "Joe"
}

But you should really map to but it should really be mapped to

{
    "People" : [ "Joe" ]
}

To fix that, the input should look like: To resolve this problem, input should be as follows:

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

And you would use the following function ( based off of other solutions, but extended a bit) you would use the following functions (based on other solutions, but extended a little)

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

#6th floor

Best Way to the include IS of The polyfill for The JSON Object. The best way is to polyfill included in JSON object.

IF you insist the Create A But Method, for serializing to JSON AN Object Notation ( ! Valid values for JSON ) Inside at The jQuery namespace, you CAN do something like the this: But if you insist to create a space in the name jQuery serialize objects into JSON representation Notation (JSON the effective value method), you can do this:

Implementation fulfillment

// 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 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);
Original articles published 0 · won praise 136 · views 830 000 +

Guess you like

Origin blog.csdn.net/xfxf996/article/details/105266575