Conversion d'un objet en chaîne

Comment puis-je convertir un objet JavaScript en chaîne?

Exemple:

var o = {a:1, b:2} console.log(o) console.log('Item: ' + o) 

Sortie:

Objet {a = 1, b = 2} // très bonne sortie lisible 🙂
Objet: [Objet objet] // aucune idée de ce qui est à l'intérieur 🙁

Je recommande d'utiliser JSON.stringify , qui sérialise un objet. La plupart des navigateurs modernes prennent en charge cette méthode de façon native, mais pour ceux qui ne le font pas, vous pouvez inclure une version JS :

 var obj = { name: 'myObj' }; JSON.stringify(obj); 

Bien sûr, pour convertir un objet en une chaîne, vous devez utiliser votre propre méthode, par exemple:

 function objToString (obj) { var str = ''; for (var p in obj) { if (obj.hasOwnProperty(p)) { str += p + '::' + obj[p] + '\n'; } } return str; } 

En fait, ce qui précède montre l'approche générale; Vous pouvez utiliser quelque chose comme http://phpjs.org/functions/var_export:578 ou http://phpjs.org/functions/var_dump:604

Ou, si vous n'utilisez pas de méthodes (fonctions en tant que propriétés de votre objet), vous pouvez utiliser la nouvelle norme (mais pas implémentée dans les navigateurs plus anciens, même si vous pouvez trouver un utilitaire pour l'aider pour eux aussi), JSON .stringify (). Mais encore une fois, cela ne fonctionnera pas si l'objet utilise des fonctions ou d'autres propriétés qui ne sont pas sérialisables pour JSON.

Utilisez la fonction javascript String ().

  String(yourobject); 

OU

 JSON.stringify(yourobject) 

.

En vous simplifiant avec la console , vous pouvez simplement utiliser une virgule au lieu d'un + . Le + tentera de convertir l'objet en une chaîne, alors que la virgule l'affichera séparément dans la console.

Exemple:

 var o = {a:1, b:2}; console.log(o); console.log('Item: ' + o); console.log('Item: ', o); // :) 

Sortie:

 Object { a=1, b=2} // useful Item: [object Object] // not useful Item: Object {a: 1, b: 2} // Best of both worlds! :) 

Référence: https://developer.mozilla.org/en-US/docs/Web/API/Console.log

EDIT Ne pas utiliser cette réponse car elle ne fonctionne pas dans Internet Explorer. Utilisez la solution Gary Chambers .

ToSource () est la fonction que vous recherchez qui l'écrira comme JSON.

 var object = {}; object.first = "test"; object.second = "test2"; alert(object.toSource()); 

Une option :

console.log('Item: ' + JSON.stringify(o));

O est imprimé en chaîne

Une autre option (comme soktinpk l'a souligné dans les commentaires), et mieux pour le débogage de console IMO:

console.log('Item: ', o);

O est imprimé comme objet, que vous pourriez analyser si vous aviez plus de champs

Aucune des solutions ici n'a été utilisée pour moi. JSON.stringify semble être ce que beaucoup de gens disent, mais il coupe les fonctions et semble assez cassé pour certains objets et tableaux que j'ai essayé lors du test.

J'ai créé ma propre solution qui fonctionne au moins dans Chrome. Le publier ici afin que quiconque regarde cela sur Google puisse le trouver.

 //Make an object a string that evaluates to an equivalent object // Note that eval() seems tricky and sometimes you have to do // something like eval("a = " + yourString), then use the value // of a. // // Also this leaves extra commas after everything, but JavaScript // ignores them. function convertToText(obj) { //create an array that will later be joined into a string. var string = []; //is object // Both arrays and objects seem to return "object" // when typeof(obj) is applied to them. So instead // I am checking to see if they have the property // join, which normal objects don't have but // arrays do. if (typeof(obj) == "object" && (obj.join == undefined)) { string.push("{"); for (prop in obj) { string.push(prop, ": ", convertToText(obj[prop]), ","); }; string.push("}"); //is array } else if (typeof(obj) == "object" && !(obj.join == undefined)) { string.push("[") for(prop in obj) { string.push(convertToText(obj[prop]), ","); } string.push("]") //is function } else if (typeof(obj) == "function") { string.push(obj.toString()) //all other values can be done with JSON.stringify } else { string.push(JSON.stringify(obj)) } return string.join("") } 

EDIT: Je sais que ce code peut être amélioré, mais ne s'est jamais déroulé pour le faire. L'utilisateur andrey a proposé une amélioration ici avec le commentaire:

Voici un petit code modifié, qui peut gérer «nul» et «indéfini», et ne pas ajouter de virgules excessives.

Utilisez-le à vos risques et périls, car je ne l'ai pas vérifié du tout. N'hésitez pas à suggérer des améliorations supplémentaires en tant que commentaire.

Si vous téléchargez simplement la console, vous pouvez utiliser console.log('string:', obj) . Notez la virgule .

Dans les cas où vous savez que l'objet est juste un Boolean, Date, String, etc … La fonction javascript String () fonctionne très bien. J'ai récemment trouvé cela utile pour traiter les valeurs issues de la fonction $ .each de jquery.

Par exemple, ce qui suit transforme tous les éléments en "valeur" en chaîne:

 $.each(this, function (name, value) { alert(String(value)); }); 

Plus de détails ici:

http://www.w3schools.com/jsref/jsref_string.asp

Je cherchais cela, et j'écrivais une récursive profonde avec indentation:

 function objToString(obj, ndeep) { if(obj == null){ return String(obj); } switch(typeof obj){ case "string": return '"'+obj+'"'; case "function": return obj.name || obj.toString(); case "object": var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj); return '{['[+isArray] + Object.keys(obj).map(function(key){ return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1); }).join(',') + '\n' + indent + '}]'[+isArray]; default: return obj.toString(); } } 

Utilisation: objToString({ a: 1, b: { c: "test" } })

 var obj={ name:'xyz', Address:'123, Somestreet' } var convertedString=JSON.stringify(obj) console.log("literal object is",obj ,typeof obj); console.log("converted string :",convertedString); console.log(" convertedString type:",typeof convertedString); 

Si vous voulez simplement voir l'objet pour le débogage, vous pouvez utiliser

 var o = {a:1, b:2} console.dir(o) 

Les méthodes JSON sont assez inférieures au moteur Gecko .toSource () primitive.

Voir la réponse de l'article SO pour les tests de comparaison.

En outre, la réponse ci-dessus se réfère à http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html qui, comme JSON, (l'autre article http: // http://Www.davidpirek.com/blog/object-to-string-how-to-deserialize-json utilise via "ExtJs JSON codent le code source" ) ne peut pas gérer les références circulaires et est incomplet. Le code ci-dessous montre ses limites (de la parodie) (corrigées pour gérer les tableaux et les objets sans contenu).

( Lien direct vers le code dans //forums.devshed.com/ … / tosource-with-arrays-in-ie-386109 )

 javascript: Object.prototype.spoof=function(){ if (this instanceof String){ return '(new String("'+this.replace(/"/g, '\\"')+'"))'; } var str=(this instanceof Array) ? '[' : (this instanceof Object) ? '{' : '('; for (var i in this){ if (this[i] != Object.prototype.spoof) { if (this instanceof Array == false) { str+=(i.match(/\W/)) ? '"'+i.replace('"', '\\"')+'":' : i+':'; } if (typeof this[i] == 'string'){ str+='"'+this[i].replace('"', '\\"'); } else if (this[i] instanceof Date){ str+='new Date("'+this[i].toGMTString()+'")'; } else if (this[i] instanceof Array || this[i] instanceof Object){ str+=this[i].spoof(); } else { str+=this[i]; } str+=', '; } }; str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+( (this instanceof Array) ? ']' : (this instanceof Object) ? '}' : ')' ); return str; }; for(i in objRA=[ [ 'Simple Raw Object source code:', '[new Array, new Object, new Boolean, new Number, ' + 'new String, new RegExp, new Function, new Date]' ] , [ 'Literal Instances source code:', '[ [], {}, true, 1, "", /./, function(){}, new Date() ]' ] , [ 'some predefined entities:', '[JSON, Math, null, Infinity, NaN, ' + 'void(0), Function, Array, Object, undefined]' ] ]) alert([ '\n\n\ntesting:',objRA[i][0],objRA[i][1], '\n.toSource()',(obj=eval(objRA[i][1])).toSource(), '\ntoSource() spoof:',obj.spoof() ].join('\n')); 

Qui affiche:

 testing: Simple Raw Object source code: [new Array, new Object, new Boolean, new Number, new String, new RegExp, new Function, new Date] .toSource() [[], {}, (new Boolean(false)), (new Number(0)), (new String("")), /(?:)/, (function anonymous() {}), (new Date(1303248037722))] toSource() spoof: [[], {}, {}, {}, (new String("")), {}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")] 

et

 testing: Literal Instances source code: [ [], {}, true, 1, "", /./, function(){}, new Date() ] .toSource() [[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))] toSource() spoof: [[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")] 

et

 testing: some predefined entities: [JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined] .toSource() [JSON, Math, null, Infinity, NaN, (void 0), function Function() {[native code]}, function Array() {[native code]}, function Object() {[native code]}, (void 0)] toSource() spoof: [{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined] 

Comme Firefox ne calcule pas certains objets comme objet d'écran; Si vous voulez avoir le même résultat, par exemple: JSON.stringify(obj) :

 function objToString (obj) { var tabjson=[]; for (var p in obj) { if (obj.hasOwnProperty(p)) { tabjson.push('"'+p +'"'+ ':' + obj[p]); } } tabjson.push() return '{'+tabjson.join(',')+'}'; } 

Jetez un oeil au plugin jQuery-JSON

À sa base, il utilise JSON.stringify mais retombe dans son propre analyseur si le navigateur ne l'implémente pas.

Si vous vous occupez uniquement des chaînes, des objets et des tableaux:

 function objectToString (obj) { var str = ''; var i=0; for (var key in obj) { if (obj.hasOwnProperty(key)) { if(typeof obj[key] == 'object') { if(obj[key] instanceof Array) { str+= key + ' : [ '; for(var j=0;j<obj[key].length;j++) { if(typeof obj[key][j]=='object') { str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}'; } else { str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings } } str+= ']' + (i > 0 ? ',' : '') } else { str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : ''); } } else { str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : ''); } i++; } } return str; } 

Si vous utilisez la base de données javascript Dojo, il existe déjà une fonction de construction pour faire ceci: dojo.toJson () qui serait utilisé comme tel.

 var obj = { name: 'myObj' }; dojo.toJson(obj); 

Qui renverra une chaîne. Si vous souhaitez convertir l'objet en données json, ajoutez un deuxième paramètre de vrai.

 dojo.toJson(obj, true); 

http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson

 /* This function is as JSON.Stringify (but if you has not in your js-engine you can use this) Params: obj - your object inc_ident - can be " " or "\t". show_types - show types of object or not ident - need for recoursion but you can not set this parameter. */ function getAsText(obj, inc_ident, show_types, ident) { var res = ""; if (!ident) ident = ""; if (typeof(obj) == "string") { res += "\"" + obj + "\" "; res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : ""; } else if (typeof(obj) == "number" || typeof(obj) == "boolean") { res += obj; res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : ""; } else if (obj instanceof Array) { res += "[ "; res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : ""; res += "\r\n"; var new_ident = ident + inc_ident; var arr = []; for(var key in obj) { arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident)); } res += arr.join(",\r\n") + "\r\n"; res += ident + "]"; } else { var new_ident = ident + inc_ident; res += "{ "; res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : ""; res += "\r\n"; var arr = []; for(var key in obj) { arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident)); } res += arr.join(",\r\n") + "\r\n"; res += ident + "}\r\n"; } return res; }; 

Exemple à utiliser:

 var obj = { str : "hello", arr : ["1", "2", "3", 4], b : true, vobj : { str : "hello2" } } var ForReading = 1, ForWriting = 2; var fso = new ActiveXObject("Scripting.FileSystemObject") f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true) f1.Write(getAsText(obj, "\t")); f1.Close(); f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true) f2.Write(getAsText(obj, "\t", true)); f2.Close(); 

Your_object1.txt:

 { "str" : "hello" , "arr" : [ "1" , "2" , "3" , 4 ], "b" : true, "vobj" : { "str" : "hello2" } } 

Your_object2.txt:

 { /* typeobj: object*/ "str" : "hello" /* typeobj: string*/, "arr" : [ /* typeobj: object*/ "1" /* typeobj: string*/, "2" /* typeobj: string*/, "3" /* typeobj: string*/, 4/* typeobj: number*/ ], "b" : true/* typeobj: boolean*/, "vobj" : { /* typeobj: object*/ "str" : "hello2" /* typeobj: string*/ } } 

Pour votre exemple, je pense que console.log("Item:",o) serait le plus simple. Mais, console.log("Item:" + o.toString) fonctionnerait également.

L'utilisation de la méthode numéro un utilise un menu déroulant agréable dans la console, donc un objet long fonctionnerait bien.

 var o = {a:1, b:2}; o.toString=function(){ return 'a='+this.a+', b='+this.b; }; console.log(o); console.log('Item: ' + o); 

Puisque Javascript v1.0 fonctionne partout (même IE), c'est une approche native et permet un aspect très coûteux de votre objet lors du débogage et de la production https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference / Global_Objects / Object / toString

Exemple utile

 var Ship=function(n,x,y){ this.name = n; this.x = x; this.y = y; }; Ship.prototype.toString=function(){ return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y; }; alert([new Ship('Star Destroyer', 50.001, 53.201), new Ship('Millennium Falcon', 123.987, 287.543), new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle! //"Star Destroyer" located at: x:50.001 y:53.201 //"Millennium Falcon" located at: x:123.987 y:287.543 //"TIE fighter" located at: x:83.06 y:102.523 

Aussi, en prime

 function ISO8601Date(){ return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate(); } var d=new Date(); d.toString=ISO8601Date;//demonstrates altering native object behaviour alert(d); //IE6 Fri Jul 29 04:21:26 UTC+1200 2016 //FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time) //d.toString=ISO8601Date; 2016-7-29 
 function objToString (obj) { var str = '{'; if(typeof obj=='object') { for (var p in obj) { if (obj.hasOwnProperty(p)) { str += p + ':' + objToString (obj[p]) + ','; } } } else { if(typeof obj=='string') { return '"'+obj+'"'; } else { return obj+''; } } return str.substring(0,str.length-1)+"}"; } 

J'espère que cet exemple aidera tous ceux qui travaillent tous sur un éventail d'objets

 var data_array = [{ "id": "0", "store": "ABC" },{ "id":"1", "store":"XYZ" }]; console.log(String(data_array[1]["id"]+data_array[1]["store"])); 
 setobjToString:function(obj){ var me =this; obj=obj[0]; var tabjson=[]; for (var p in obj) { if (obj.hasOwnProperty(p)) { if (obj[p] instanceof Array){ tabjson.push('"'+p +'"'+ ':' + me.setobjToString(obj[p])); }else{ tabjson.push('"'+p +'"'+':"'+obj[p]+'"'); } } } tabjson.push() return '{'+tabjson.join(',')+'}'; }