Convertir objeto JS a cadena JSON


Si definí un objeto en JS con:

var j={"name":"binchen"};

¿Cómo puedo convertir el objeto a JSON? La cadena de salida debe ser:

'{"name":"binchen"}'
Author: KARTHIKEYAN.A, 2010-11-12

26 answers

Todos los navegadores actuales tienen soporte nativo JSON incorporado. Así que mientras no estés tratando con navegadores prehistóricos como IE6 / 7 puedes hacerlo tan fácilmente como eso:

var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'
 1643
Author: Andris,
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-04-15 19:08:37

Con JSON.stringify() encontrado en json2.js o nativo en la mayoría de los navegadores modernos.

   JSON.stringify(value, replacer, space)
        value       any JavaScript value, usually an object or array.

       replacer    an optional parameter that determines how object
                    values are stringified for objects. It can be a
                    function or an array of strings.

       space       an optional parameter that specifies the indentation
                    of nested structures. If it is omitted, the text will
                    be packed without extra whitespace. If it is a number,
                    it will specify the number of spaces to indent at each
                    level. If it is a string (such as '\t' or ' '),
                    it contains the characters used to indent at each level.

       This method produces a JSON text from a JavaScript value.
 93
Author: Ignacio Vazquez-Abrams,
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-13 18:06:47

Echa un vistazo actualizado / mejor manera:

Actualización 17 de mayo de 2008: Pequeño desinfectante añadido al método toObject. Ahora toObject() no eval() la cadena si encuentra algún código malicioso en se.Para aún más seguridad: No configure el indicador includeFunctions es true.

Douglas Crockford, padre del concepto JSON, escribió uno de los primeros stringifiers para JavaScript. Más tarde Steve Yen en Trim Path escribió una buena versión mejorada que he utilizado durante algún tiempo. Son mis cambios a la versión de Steve que me gustaría compartir con ustedes. Básicamente se derivaron de mi deseo de hacer el stringifier:

• handle and restore cyclical references  
• include the JavaScript code for functions/methods (as an option)  
• exclude object members from Object.prototype if needed.
 25
Author: Sarfraz,
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
2010-11-12 08:26:33

Puede usar JSON.stringify () método para convertir el objeto JSON en String.

var j={"name":"binchen"};
JSON.stringify(j)

Para el proceso inverso, puede usar JSON.método parse () para convertir una cadena JSON a un objeto JSON.

 15
Author: Aravind Sachin,
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-11-20 10:05:55

Json Stringify puede convertir su objeto js a json

 var x = {"name" : "name1"};
 JSON.stringify(x);
 13
Author: Aatif Bandey,
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-11-03 12:01:00
JSON.stringify({"key":"value"});
 9
Author: Om Prakash,
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-06-25 14:38:08

Si estás usando AngularJS, el filtro' json ' debería hacerlo:

<span>{{someObject | json}}</span>
 7
Author: Ariel Cabib,
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-09-11 05:38:45

En AngularJS

angular.toJson(obj, pretty);

Obj: Entrada que se serializará en JSON.

Bastante (opcional):
Si se establece en true, la salida JSON contendrá líneas nuevas y espacios en blanco. Si se establece en un entero, la salida JSON contendrá tantos espacios por sangría.

(por defecto: 2)

 7
Author: Nazrul Islam,
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-17 08:42:18

JSON.stringify convierte un objeto Javascript en texto JSON y almacena ese texto JSON en una cadena.

La conversión es un Objeto a String

JSON.parse convierte una cadena de texto JSON en un objeto Javascript.

La conversión es una cadena a Objeto

var j={"name":"binchen"};

Para convertirlo en una cadena JSON se podría usar el siguiente.

JSON.stringify({"key":"value"});

JSON.stringify({"name":"binchen"});

Para más información puede consultar este enlace debajo.

Https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

 6
Author: Dulith De Costa,
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-02-13 13:15:38

JSON.stringify(j,null,4) le daría JSON embellecido en caso de que necesite embellecimiento también

 5
Author: Vignesh Murugan,
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-11-15 14:21:42
var someObj = { "name" : "some name" };
var someObjStr = JSON.stringify(someObj);
console.log( someObjStr  );
 4
Author: Tyler Durden,
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-06-29 07:36:31

Estaba teniendo problemas con stringify que se quedaba sin memoria y otras soluciones no parecían funcionar (al menos no pude hacer que funcionaran), que es cuando me tropecé con este hilo. Gracias a Rohit Kumar Acabo de iterar a través de mi objeto JSON muy grande para evitar que se estrelle

var j = MyObject;
var myObjectStringify = "{\"MyObject\":[";
var last = j.length
var count = 0;
for (x in j) {
    MyObjectStringify += JSON.stringify(j[x]);
    count++;
    if (count < last)
        MyObjectStringify += ",";
}
MyObjectStringify += "]}";

MyObjectStringify te daría tu string representaion (tal como se mencionó otras veces en este hilo) excepto si tienes un objeto grande, esto también debería funcionar - solo asegúrate de que build it to fit your needs - Necesitaba que tuviera un nombre que array

 4
Author: Sam,
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-05-23 11:47:34

Una costumbre definida para esto , hasta que lo hagamos extraño del método stringify

var j={"name":"binchen","class":"awesome"};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j)
{
json += dq+x+dq+":"+dq+j[x]+dq;
count++;
if(count<last)
   json +=",";
}
json+="}";
document.write(json);

SALIDA

{"name":"binchen","class":"awesome"}

EN VIVO http://jsfiddle.net/mailmerohit5/y78zum6v /

 3
Author: Rohit Kumar,
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-10-12 09:57:45

const obj = { "name":"xxx", "city":"York"};
const myJSON = JSON.stringify(obj);
  console.log(myJSON);
 3
Author: Arvind Audacious,
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-05-23 12:54:01

Woking... Fácil de usar

$("form").submit(function(evt){
  evt.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvert = JSON.stringify(formData);  // Convert to json
});

Gracias

 2
Author: Subroto Biswas,
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-11-28 03:39:40

Basta con copiar y pasar

$("form").submit(function(evt){
  evt.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
});
 2
Author: Subroto Biswas,
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-11-28 03:42:50

Puede usar la función nativa stringify como esta

const j={ "name": "binchen" }

/** convert json to string */
const jsonString = JSON.stringify(j)

console.log(jsonString) // {"name":"binchen"}
 1
Author: Alongkorn Chetasumon,
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 10:37:56

Si desea obtener el valor de las propiedades json en formato de cadena, use la siguiente manera

var i = {"x":1}

var j = JSON.stringify(i.x);

var k = JSON.stringify(i);

console.log(j);

"1"

console.log(k);

'{"x":1}'
 1
Author: KARTHIKEYAN.A,
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-11-29 15:10:30

Definir objeto

let obj = {
"firstname" : "Hello",
"lastname" : "javascript"

};

Luego conviértalo en cadena usando este código

strObj= JSON.stringify(obj);

Para asegurarse de consolar el resultado

console.log(strObj);
 1
Author: nada diaa,
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-10-28 00:08:45

Todo lo que necesita es agregar este código a continuación
var j={"name":"binchen"}; JSON.stringify(j); // '{"name":"binchen"}'

 0
Author: ubastosir,
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-22 12:36:35

Para depurar en el nodo JS puede usar util.inspect () . Funciona mejor con referencias circulares.

var util = require('util');
var j = {name: "binchen"};
console.log(util.inspect(j));
 0
Author: Pavel Netesa,
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-03-02 16:31:07

Puede usar JSON.stringify () para hacer eso.

 0
Author: Mitesh Panchal,
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-03-27 07:07:24

Los reemplazos JSON existentes eran demasiado para mí, así que escribí mi propia función. Esto parece funcionar, pero puede que me haya perdido varios casos extremos (que no ocurren en mi proyecto). Y probablemente no funcionará para ningún objeto preexistente, solo para datos hechos por sí mismos.

function simpleJSONstringify(obj) {
    var prop, str, val,
        isArray = obj instanceof Array;

    if (typeof obj !== "object") return false;

    str = isArray ? "[" : "{";

    function quote(str) {
        if (typeof str !== "string") str = str.toString();
        return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"'
    }

    for (prop in obj) {
        if (!isArray) {
            // quote property
            str += quote(prop) + ": ";
        }

        // quote value
        val = obj[prop];
        str += typeof val === "object" ? simpleJSONstringify(val) : quote(val);
        str += ", ";
    }

    // Remove last colon, close bracket
    str = str.substr(0, str.length - 2)  + ( isArray ? "]" : "}" );

    return str;
}
 0
Author: Hauke,
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-05-30 09:40:14
So in order to convert a js object to JSON String: 

La sintaxis simple para convertir un objeto en una cadena es

JSON.stringify(value)

La sintaxis completa es: JSON.stringify (value[, replacer[, space]])

Veamos algunos ejemplos sencillos. Tenga en cuenta que toda la cadena obtiene comillas dobles y todos los datos de la cadena se escapan si necesario.

JSON.stringify("foo bar"); // ""foo bar""
JSON.stringify(["foo", "bar"]); // "["foo","bar"]"
JSON.stringify({}); // '{}'
JSON.stringify({'foo':true, 'baz':false}); /* " 
{"foo":true,"baz":false}" */



const obj = { "property1":"value1", "property2":"value2"};
const JSON_response = JSON.stringify(obj);
console.log(JSON_response);/*"{ "property1":"value1", 
"property2":"value2"}"*/
 0
Author: Rahul Choudhary,
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-10-03 05:56:31

Lo que quieres es :

var yourObject = {a : "string", b : 2 };
Json.Stringify(yourObject);

De cualquier manera, si desea una impresión bonita, debe verificar: ¿Cómo puedo imprimir JSON con JavaScript?

Más compruebe esto para obtener información sobre JSON stringify / parse.

 -1
Author: Tiago Loureiro,
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-08-09 15:05:07

Si tienes una cadena json y no está envuelta con [] entonces envuélvela primero

var str = '{"city": "Tampa", "state": "Florida"}, {"city": "Charlotte", "state": "North Carolina"}';
str = '[' + str + ']';
var jsonobj = $.parseJSON(str);

O

var jsonobj = eval('(' + str + ')');
console.log(jsonobj);
 -19
Author: Bhaumik Mehta,
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-16 06:13:14