web-dev-qa-db-fra.com

Conversion d'un objet en chaîne

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

Exemple:

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

Sortie:

Objet {a = 1, b = 2} // très belle sortie lisible :)
Item: [object Object] // aucune idée de ce qu'il y a à l'intérieur :(

863
user680174

Je recommanderais d'utiliser JSON.stringify , qui convertit l'ensemble des variables de l'objet en une chaîne JSON. La plupart des navigateurs modernes supportent cette méthode de manière native, mais pour ceux qui ne le font pas, vous pouvez inclure une version de JS

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);
1235
Gary Chambers

Utilisez la fonction javascript String ().

 String(yourobject); //returns [object Object]

ou

JSON.stringify(yourobject)

.

89
Vikram Pote

Bien sûr, pour convertir un objet en chaîne, vous devez soit utiliser votre propre méthode, telle que:

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 ne fait que montrer l’approche générale; vous voudrez peut-être 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 pourrez peut-être utiliser le nouveau standard (mais pas implémenté dans les navigateurs plus anciens, mais vous pouvez également trouver un utilitaire pour les aider), 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 en JSON.

84
Brett Zamir

En conservant la simplicité avec console, vous pouvez simplement utiliser une virgule au lieu d'un +. Le + essaiera de convertir l'objet en 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

68
Luke

EDIT N'utilisez pas cette réponse car elle ne fonctionne pas dans Internet Explorer. Utilisez Gary Chambers solution.

toSource () est la fonction que vous recherchez et qui l'écrira au format JSON.

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

Aucune des solutions ici ne fonctionnait pour moi. JSON.stringify semble être ce que beaucoup de gens disent, mais il supprime les fonctions et semble assez cassé pour certains objets et tableaux que j'ai essayés lors du test.

J'ai créé ma propre solution, qui fonctionne au moins sous Chrome. Publiez-le ici pour que tous ceux qui consultent Google puissent 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 je n’ai jamais réussi à le faire. L'utilisateur andrey a suggéré une amélioration ici avec le commentaire:

Voici un code légèrement modifié, qui peut gérer les valeurs "null" et "indéfini", sans ajouter de virgule excessive.

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

20
Houshalter

Si vous ne sortez que vers la console, vous pouvez utiliser console.log('string:', obj). Notez la virgule.

19
Alexandre R. Janini

Dans les cas où vous savez que l'objet est simplement un booléen, une date, une chaîne, un nombre, etc. J'ai récemment trouvé cela utile pour gérer les valeurs provenant de la fonction $ .each de jquery.

Par exemple, ce qui suit convertirait tous les éléments de "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

15
Jake Drew
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);
13
sunny rai

Je cherchais ceci et en ai écrit un profond 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();
  }
}

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

10
SylvainPV

Si vous voulez juste voir l’objet pour le débogage, vous pouvez utiliser

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

1.

JSON.stringify(o);

Item: {"a": "1", "b": "2"}

2.

var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.Push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);

Élément: {a: 1, b: 2}

7
vacsati

Les méthodes JSON sont très inférieures à la primitive .toSource () du moteur Gecko.

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

De même, la réponse ci-dessus fait référence à http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html qui, comme JSON, ( que l’autre article http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json utilise via "Le code source JSON ExtJs" ) ne peut pas traiter circulaire références et est incomplète. Le code ci-dessous montre ses limitations (spoof's) (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]
6
Ekim

En tant que firefox, aucun objet n'est défini comme un objet d'écran. si vous voulez avoir le même résultat tel que: 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(',')+'}';
}
4
Abdennour TOUMI

stringify-object est une bonne bibliothèque npm faite par l’équipe yeoman: https://www.npmjs.com/package/stringify-object

npm install stringify-object

puis: 

const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);

Évidemment, ce n’est intéressant que si vous avez un objet circulaire qui échouerait avec JSON.stringify();

3
Nicolas Zozol

Regardez le jQuery-JSON plugin

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

3
Evan Plaice

Si vous ne vous souciez que 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;
    }
3
Anuraag Vaidya
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 dans IE), il s'agit d'une approche native qui permet de personnaliser l'apparence de votre objet lors du débogage et de la production https://developer.mozilla.org/fr/docs/Web/JavaScript/Référence/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 bonus

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
2
Alex

Pour votre exemple, je pense que console.log("Item:",o) Serait plus facile. Mais, console.log("Item:" + o.toString) Fonctionnerait également.

La première méthode utilise un menu déroulant de Nice dans la console pour qu'un objet long fonctionne correctement.

1
Fuzzyzilla

Si vous utilisez le framework javascript de Dojo, il existe déjà une fonction de construction permettant de le faire: dojo.toJson (), qui serait utilisé comme suit 

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

qui retournera une chaîne. Si vous voulez convertir l'objet en données json, ajoutez un deuxième paramètre de true.

dojo.toJson(obj, true);

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

1
Chris O'Connell
/*
    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();

votre_objet1.txt:

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

}

votre_objet2.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*/
    }

}
1
sea-kg

Pour les objets non imbriqués:

Object.entries(o).map(x=>x.join(":")).join("\r\n")
1
Alex Szücs

Si tout ce que vous voulez, c'est simplement obtenir une sortie de chaîne, alors ceci devrait fonctionner: String(object)

1
Moe

J'avais besoin de créer une version plus configurable de JSON.stringify car je devais ajouter des commentaires et connaître le chemin JSON:

const someObj = {
  a: {
    nested: {
      value: 'Apple',
    },
    sibling: 'peanut'
  },
  b: {
    languages: ['en', 'de', 'fr'],
    c: {
      Nice: 'heh'
    }
  },
  c: 'butter',
  d: function () {}
};

function* objIter(obj, indent = '  ', depth = 0, path = '') {
  const t = indent.repeat(depth);
  const t1 = indent.repeat(depth + 1);
  const v = v => JSON.stringify(v);
  yield { type: Array.isArray(obj) ? 'OPEN_ARR' : 'OPEN_OBJ', indent, depth };
  const keys = Object.keys(obj);
  
  for (let i = 0, l = keys.length; i < l; i++) {
    const key = keys[i];
    const prop = obj[key];
    const nextPath = !path && key || `${path}.${key}`;
 
    if (typeof prop !== 'object') {
      yield { type:  isNaN(key) ? 'VAL' : 'ARR_VAL', key, prop, indent, depth, path: nextPath };
    } else {
      yield { type: 'OBJ_KEY', key, indent, depth, path: nextPath };
      yield* objIter(prop, indent, depth + 1, nextPath);
    }
  }

  yield { type: Array.isArray(obj) ? 'CLOSE_ARR' : 'CLOSE_OBJ', indent, depth };
}

const iterMap = (it, mapFn) => {
  const arr = [];
  for (const x of it) { arr.Push(mapFn(x)) }
  return arr;
}

const objToStr = obj => iterMap(objIter(obj), ({ type, key, prop, indent, depth, path }) => {
  const t = indent.repeat(depth);
  const t1 = indent.repeat(depth + 1);
  const v = v => JSON.stringify(v);

  switch (type) {
    case 'OPEN_ARR':
      return '[\n';
    case 'OPEN_OBJ':
      return '{\n';
    case 'VAL':
      return `${t1}// ${path}\n${t1}${v(key)}: ${v(prop)},\n`;
    case 'ARR_VAL':
      return `${t1}// ${path}\n${t1}${v(prop)},\n`;
    case 'OBJ_KEY':
      return `${t1}// ${path}\n${t1}${v(key)}: `;
    case 'CLOSE_ARR':
    case 'CLOSE_OBJ':
      return `${t}${type === 'CLOSE_ARR' ? ']' : '}'}${depth ? ',' : ';'}\n`;
    default:
      throw new Error('Unknown type:', type);
  }
}).join('');

const s = objToStr(someObj);
console.log(s);

0
Dominic
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)+"}";
}
0
Mauro

Si vous ne voulez pas joindre le jeu () à Object.

const obj = {one:1, two:2, three:3};
let arr = [];
for(let p in obj)
    arr.Push(obj[p]);
const str = arr.join(',');
0

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

var data_array = [{
                    "id": "0",
                    "store": "ABC"
                },{
                    "id":"1",
                    "store":"XYZ"
                }];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
0
Khushal Chheda

Il manque en fait une option simple (pour les navigateurs récents et Node.js) dans les réponses existantes:

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

Je préférerais cela car JSON.stringify() a certaines limitations (par exemple avec des structures circulaires).

0
Christian Gawron

Si vous pouvez utiliser lodash, vous pouvez le faire de cette façon:

> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'

Avec lodash map(), vous pouvez également effectuer une itération sur les objets . Ceci associe chaque entrée clé/valeur à sa représentation sous forme de chaîne:

> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]

Et join() rassemble les entrées du tableau.

Si vous pouvez utiliser ES6 Template String, cela fonctionne aussi:

> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'

S'il vous plaît noter que cela ne va pas récursif à travers l'objet:

> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]

Comme la fonction util.inspect() du noeud fera:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'
0
kwarnke

Si vous voulez une méthode minimaliste de conversion d'une variable en chaîne pour une situation de type expression en ligne, ''+variablename est le meilleur que j'ai joué au golf.

Si 'variablename' est un objet et que vous utilisez l'opération de concaténation de chaînes vides, la réponse ennuyée [object Object] sera donnée, auquel cas vous voudrez probablement de la réponse JSON.stringify énervée de Gary C. à lire sur Mozilla Réseau de développeurs sur le lien dans qui répond en haut .

0
stackuser83

Il semble que JSON accepte le deuxième paramètre qui pourrait aider avec les fonctions - replacer , cela résout le problème de la conversion de la manière la plus élégante:

JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return String(val);
    }
    return val;
  });
0
Gleb Dolzikov