Serialización a JSON en jQuery [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Necesito serializar un objeto en JSON. Estoy usando jQuery. ¿Hay una forma "estándar" de hacer esto?

Mi situación específica: Tengo una matriz definida como se muestra a continuación:

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

Y necesito convertir esto en una cadena para pasar a $.ajax() como esto:

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

11 answers

JSON-js - JSON en JavaScript.

Para convertir un objeto en una cadena, use JSON.stringify:

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

Para convertir una cadena JSON en objeto, use JSON.parse:

var your_object = JSON.parse(json_text);

Fue recientemente recomendado por John Resig:

...POR FAVOR, comience a migrar su JSON-usando aplicaciones a Crockford es json2.js. Es totalmente compatible con ECMAScript 5 especificación y se degrada con gracia si un nativo(más rápido !) aplicación existir.

De hecho, acabo de aterrizar un cambio en jQuery ayer que utiliza el JSON.método de análisis si existe, ahora que ha sido completamente especificado.

Tiendo a confiar en lo que dice sobre JavaScript importa:)

Los navegadores más nuevos soportan el objeto JSON de forma nativa. La versión actual de la biblioteca JSON de Crockford solo definirá JSON.stringify y JSON.parse si aún no están definidos, dejando intacta cualquier implementación nativa del navegador.

 1099
Author: Community,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-09 14:57:28

He estado usando jquery-json durante 6 meses y funciona muy bien. Es muy simple de usar:

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

// Result: {"foo":"bar","baz":"wockaflockafliz"}
 182
Author: Jay Taylor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-01 21:40:58

Funciona en IE8+

No necesita jQuery, use:

JSON.stringify(countries); 
 94
Author: pestatije,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-17 10:30:52

No lo he usado, pero es posible que desee probar el jQuery plugin escrito por Mark Gibson

Añade las dos funciones: $.toJSON(value), $.parseJSON(json_str, [safe]).

 44
Author: Tahir Akhtar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-15 14:58:56

No, la forma estándar de serializar a JSON es usar una biblioteca de serialización JSON existente. Si usted no desea hacer esto, entonces usted va a tener que escribir sus propios métodos de serialización.

Si desea orientación sobre cómo hacer esto, le sugiero que examine la fuente de algunas de las bibliotecas disponibles.

EDIT: No voy a decir que escribir sus propios métodos de serliazation es malo, pero debe considerar que si es importante para su aplicación para utilice JSON bien formado, entonces usted tiene que sopesar la sobrecarga de "una dependencia más" contra la posibilidad de que sus métodos personalizados pueden encontrar un día un caso de fallo que no había previsto. Si ese riesgo es aceptable es su decisión.

 35
Author: Adam Bellaire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-10 15:47:13

Encontré esto en alguna parte. Aunque no puedo recordar dónde... probablemente en 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;
};
 27
Author: jmort253,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-10 08:33:30

Si no desea utilizar bibliotecas externas, existe el método JavaScript nativo .toSource(), pero no es perfectamente cross-browser.

 11
Author: Kain Haart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-17 15:49:15

La mejor manera es incluir el polyfill para el objeto JSON.

Pero si insiste en crear un método para serializar un objeto en notación JSON (valores válidos para JSON) dentro del espacio de nombres jQuery, puede hacer algo como esto:

Aplicación

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

Uso

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);
 10
Author: jherax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-14 21:35:05

Sí, deberías usar JSON.stringify y JSON.analiza tu "Json_PostData" antes de llamar a $.ajax

   $.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
Author: bruce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-24 03:50:13

Es básicamente un proceso de 2 pasos:

Primero, necesitas stringify así

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

Después de eso, debe convertir la cadena en Objeto

var obj = JSON.parse(JSON_VAR);
 8
Author: Shrish Shrivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-07 08:29:30

Una cosa que las soluciones anteriores no tienen en cuenta es si tiene una matriz de entradas, pero solo se suministró un valor.

Por ejemplo, si el back-end espera una serie de Personas, pero en este caso particular, solo se trata de una sola persona. Entonces haciendo:

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

Luego, con las soluciones anteriores, simplemente se asignaría a algo como:

{
    "People" : "Joe"
}

Pero realmente debería mapearse a

{
    "People" : [ "Joe" ]
}

Para arreglar eso, la entrada debe mirar como:

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

Y usaría la siguiente función (basada en otras soluciones, pero extendida un poco)

$.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;
};
 7
Author: Tim Burkhart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-18 17:50:38