javascript - returns - stringify object js
Serializando para JSON no jQuery (8)
É basicamente um processo de 2 etapas:
Primeiro, você precisa se adequar assim
var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2);
Depois disso, você precisa converter a string para Object
var obj = JSON.parse(JSON_VAR);
Esta questão já tem uma resposta aqui:
- Serializando um objeto para respostas JSON 3
Eu preciso serializar um objeto para JSON. Estou usando o jQuery. Existe uma maneira "padrão" de fazer isso?
Minha situação específica: Eu tenho uma matriz definida como mostrado abaixo:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
e eu preciso transformar isso em uma string para passar para $.ajax()
assim:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
A melhor maneira é incluir o polyfill para o objeto JSON-js .
Mas se você insiste em criar um método para serializar um objeto para a notação JSON ( valores válidos para JSON ) dentro do namespace do jQuery, você pode fazer algo assim:
Implementação
// 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);
Eu não usei isso, mas você pode querer experimentar o plugin jQuery escrito por Mark Gibson
Ele adiciona as duas funções: $.toJSON(value)
, $.parseJSON(json_str, [safe])
.
Eu tenho usado jquery-json por 6 meses e funciona muito bem. É muito simples de usar:
var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);
// Result: {"foo":"bar","baz":"wockaflockafliz"}
Se você não quiser usar bibliotecas externas, existe o método JavaScript nativo .toSource()
, mas não é perfeitamente .toSource()
com o navegador.
Sim, você deve JSON.stringify e JSON.parse seu "Json_PostData" antes de chamar $ .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");
}
});
JSON-js - JSON em JavaScript.
Para converter um objeto em uma string, use JSON.stringify
:
var json_text = JSON.stringify(your_object, null, 2);
Para converter uma string JSON em objeto, use JSON.parse
:
var your_object = JSON.parse(json_text);
Foi recentemente recomendado por John Resig :
... POR FAVOR, comece a migrar seus aplicativos usando JSON para o json2.js do Crockford. É totalmente compatível com a especificação do ECMAScript 5 e normalmente se degrada se existir uma implementação nativa (mais rápida!).
Na verdade, acabei de receber uma alteração no jQuery ontem que utiliza o método JSON.parse, se existir, agora que foi completamente especificado.
Eu costumo confiar no que ele diz sobre questões de JavaScript :)
Novos navegadores suportam o objeto JSON nativamente. A versão atual da biblioteca JSON de Crockford só definirá JSON.stringify
e JSON.parse
se eles ainda não estiverem definidos, deixando a implementação nativa do navegador intacta.