Diferencia entre JSON.stringify y JSON.analizar
He estado confundido sobre cuándo usar estos dos métodos de análisis.
Después de hacer eco de mis datos json_encoded y recuperarlos a través de ajax, a menudo me encuentro con confusión sobre cuándo debo usar JSON.stringify y JSON.parse .
Obtengo [object,object]
en mi consola.log cuando se analiza y un objeto de JavaScript cuando string.
$.ajax({
url: "demo_test.txt",
success: function(data) {
console.log(JSON.stringify(data))
/* OR */
console.log(JSON.parse(data))
//this is what I am unsure about?
}
});
15 answers
JSON.stringify
convierte un objeto JavaScript en texto JSON y almacena ese texto JSON en una cadena.
JSON.parse
convierte una cadena de texto JSON en un objeto JavaScript.
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
2018-07-18 15:36:36
JSON.parse()
es para "analizar", algo que fue recibido como JSON.JSON.stringify()
es crear una cadena JSON a partir de un objeto/matriz.
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
2015-08-15 14:18:37
Son el inverso uno del otro. JSON.stringify()
serializa un objeto JS en una cadena JSON, mientras que JSON.parse()
se deserializar una cadena JSON en un objeto JS.
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
2015-08-08 13:59:50
En primer lugar, la función JSON.stringify()
convierte un valor JavaScript en una cadena de Notación de objetos JavaScript (JSON). JSON.parse()
la función convierte una cadena de Notación de objetos JavaScript (JSON) en un objeto. Para obtener más información sobre estas dos funciones, consulte los siguientes enlaces.
Https://msdn.microsoft.com/library/cc836459 (v=vs.94). aspx https://msdn.microsoft.com/library/cc836466 (v=vs.94). aspx
En segundo lugar, el siguiente ejemplo le será útil para: entender estas dos funciones.
<form id="form1" runat="server">
<div>
<div id="result"></div>
</div>
</form>
<script>
$(function () {
//define a json object
var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };
//use JSON.stringify to convert it to json string
var jsonstring = JSON.stringify(employee);
$("#result").append('<p>json string: ' + jsonstring + '</p>');
//convert json string to json object using JSON.parse function
var jsonobject = JSON.parse(jsonstring);
var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';
$("#result").append('<p>json object:</p>');
$("#result").append(info);
});
</script>
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-01-04 20:51:16
Son los opuestos el uno del otro.
JSON.stringify()
JSON.stringify () serializa un objeto JS en una cadena JSON.
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify('foo'); // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'
JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
// '"2006-01-02T15:04:05.000Z"'
JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
// '[1,"false",false]'
JSON.analizar()
El JSON.el método parse () analiza una cadena como JSON, transformando opcionalmente el valor producido.
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
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-04-12 06:36:07
var log = { "page": window.location.href,
"item": "item",
"action": "action" };
log = JSON.stringify(log);
console.log(log);
console.log(JSON.parse(log));
//La salida será:
/ / Para 1st Console es una Cadena Como:
'{ "page": window.location.href,"item": "item","action": "action" }'
/ / Para 2nd Console es un Objeto Como:
Object {
page : window.location.href,
item : "item",
action : "action" }
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-12-03 00:52:56
JSON.stringify()
Convierte un objeto en una cadena.
JSON.parse()
Convierte una cadena JSON en un objeto.
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
2015-04-08 05:42:25
La verdadera confusión aquí no es sobre parse vs stringify, es sobre el tipo de datos del parámetro data
de la devolución de llamada de éxito.
data
puede ser la respuesta raw, es decir, una cadena, o puede ser un objeto JavaScript, según la documentación:
Éxito
Type: Function (Anything data, String textStatus, jqXHR jqXHR ) A función a llamar si la solicitud tiene éxito. La función obtiene pasó tres argumentos: Los datos devueltos desde el servidor, formatear según el parámetro DataType o la devolución de llamada del filtro de datos función, si se especifica;<..>
Y el tipo de datos predeterminado es 'intelligent guess'
Tipo de datos (predeterminado: Conjetura inteligente (xml, json, script o html))
Type: String El tipo de datos que esperas de la servidor. Si no se especifica ninguno, jQuery intentará inferirlo basado en Tipo MIME de la respuesta (un tipo MIME XML producirá XML, en 1.4 JSON producirá un objeto JavaScript, en 1.4 script ejecutará el script, y cualquier otra cosa será devuelta como una cadena).
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-04-21 01:28:25
Son completamente opuestos el uno del otro.
JSON.parse()
se utiliza para el análisis de los datos recibidos como JSON; esto es deserializa un string JSON en a objeto de JavaScript.
JSON.stringify()
por otro lado se utiliza para crear un string JSON de un object o de la matriz de; esto es serializa un JavaScript object en a JSON cadena.
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-09-23 09:57:06
JSON.stringify(obj [, replacer [, space]])
- Toma cualquier objeto serializable y devuelve la representación JSON como una cadena.
JSON.parse(string)
- Toma una cadena JSON bien formada y devuelve el objeto JavaScript correspondiente.
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-11-08 10:15:59
Objeto JavaScript Cadena JSON
JSON.stringify() <-> JSON.parse()
JSON.stringify (obj) - Toma cualquier objeto serializable y devuelve la representación JSON como una cadena.
JSON.stringify() -> Object To String.
JSON.parse (string) - Toma una cadena JSON bien formada y devuelve el objeto JavaScript correspondiente.
JSON.parse() -> String To Object.
Explicación: JSON.stringify (obj [, replacer [, space]]);
Replacer / Space-opcional o toma valor entero o puede llamar a interger type return función.
function replacer(key, value) {
if (typeof value === 'number' && !isFinite(value)) {
return String(value);
}
return value;
}
- Reemplazar Solo use para reemplazar no finito con null.
- Uso del espacio para indentar una cadena Json por espacio
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-05-10 05:08:43
Se están oponiendo entre sí.
JSON.Stringify()
convierte JSON en cadena y JSON.Parse()
analiza una cadena en JSON.
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-07-09 09:55:36
No se si ha sido mencionado, pero uno de los usos de JSON.parse (JSON.stringify (myObject)) es crear un clon del objeto original.
Esto es útil cuando se quiere meter con algunos datos sin afectar al objeto original. Probablemente no sea la forma más limpia / rápida, pero ciertamente la más simple para objetos que no son masivamente complejos.
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-23 18:19:30
JSON : Se utiliza principalmente para intercambiar datos hacia/desde el servidor. Antes de enviar el objeto JSON al servidor, tiene que ser una cadena.
JSON.stringify() //Converts the JSON object into the string representation.
var jsonData={"Name":"ABC","Dept":"Software"};// It is a JSON object
var jsonString=JSON.stringify(jsonData);// It is a string representation of the object
// jsonString === '{"Name":"ABC","Dept":"Software"}'; is true
También convierte la matriz Javascript en cadena
var arrayObject=["ABC","Software"];// It is array object
var arrString=JSON.stringify(array);// It is string representation of the array (object)
// arrString === '["ABC","Software"]'; is true
Cuando recibimos los datos JSON del servidor, los datos serían el formato de cadena.Por lo tanto, convertimos la cadena en objeto JSON.
JSON.parse() //To convert the string into JSON object.
var data='{ "name":"ABC", "Dept":"Software"}'// it is a string (even though it looks like an object)
var JsonData= JSON.parse(data);// It is a JSON Object representation of the string.
// JsonData === { "name":"ABC", "Dept":"Software"}; is true
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-12-03 00:47:51
JSON.parse()
se utiliza para convertir Cadena a Objeto.JSON.stringify()
se utiliza para convertir Objeto a Cadena.
Puedes referirte a esto también...
<script type="text/javascript">
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open("GET", "JSON/mylist.json", true);
hr.setRequestHeader("Content-type", "application/json",true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
/* var return_data = hr.responseText; */
var data=JSON.parse(hr.responseText);
var status=document.getElementById("status");
status.innerHTML = "";
/* status.innerHTML=data.u1.country; */
for(var obj in data)
{
status.innerHTML+=data[obj].uname+" is in "+data[obj].country+"<br/>";
}
}
}
hr.send(null);
status.innerHTML = "requesting...";
}
</script>
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-12-03 00:50:18