Conversion d'un objet en chaîne

comment convertir un objet JavaScript en chaîne de caractères?

exemple:

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

sortie:

Objet { a=1, b=2} // très agréable lisible de sortie :)

Item: [object object] // aucune idée de ce qui est à l'intérieur :(

811
demandé sur meetar 2011-04-10 19:35:44

29 réponses

je recommande d'utiliser JSON.stringify , qui convertit l'ensemble des variables de l'objet en une chaîne JSON. La plupart des navigateurs modernes prennent en charge cette méthode nativement, mais pour ceux qui ne le font pas, vous pouvez inclure une version JS :

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);
1149
répondu Gary Chambers 2018-07-03 14:13:08

utiliser la fonction Javascript String ().

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

ou

JSON.stringify(yourobject)

.

84
répondu Vikram Pote 2018-04-21 12:48:25

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

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 juste l'approche générale; vous pouvez vouloir 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 être en mesure d'utiliser la nouvelle norme (mais pas mis en œuvre dans les navigateurs plus anciens, bien que vous pouvez trouver un utilitaire pour aider avec elle 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 à JSON.

82
répondu Brett Zamir 2011-08-26 11:24:04

pour rester simple avec console , vous pouvez utiliser une virgule au lieu d'une + . Le + essaiera de convertir l'objet en chaîne, tandis 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

64
répondu Luke 2015-01-07 16:23:38

EDIT N'utilisez pas cette réponse car elle ne fonctionne pas dans Internet Explorer. Utiliser 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());
32
répondu Gazler 2017-05-23 11:47:29

Une option :

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

o is printed as a string

une Autre option (comme soktinpk , a souligné dans les commentaires), et mieux pour la console de débogage de l'OMI:

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

o is printed as an object, which you could drill down if you had more fields

28
répondu nabn 2015-06-19 05:42:15

aucune des solutions ici n'a fonctionné 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é en le testant.

j'ai fait ma propre solution qui fonctionne au moins en Chrome. Le poster ici afin que quiconque qui cherche cela sur Google peut 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 eu le temps de le faire. L'utilisateur andrey suggéré une amélioration ici avec le commentaire:

voici un petit peu de code modifié, qui peut gérer 'null' et 'undefined', et aussi ne pas ajouter de virgule excessive.

utilisez ça à vos risques et périls car je ne l'ai pas du tout vérifié. Hésitez pas à suggérer d'autres améliorations comme un commentaire.

20
répondu Houshalter 2015-09-20 03:45:55

si vous n'êtes qu'une sortie vers la console, vous pouvez utiliser console.log('string:', obj) . Notez le virgule .

18
répondu Alexandre R. Janini 2014-08-14 12:53:24

dans les cas où vous savez que l'objet est juste un booléen, Date, chaîne, numéro, etc... La fonction Javascript String () fonctionne très bien. J'ai récemment trouvé ça utile pour gérer les valeurs provenant des $de jquery.chaque fonction.

par exemple, ce qui suit convertirait tous les éléments de "valeur" en une chaîne de caractères:

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

plus de détails ici:

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

14
répondu Jake Drew 2013-07-11 04:12:27
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
répondu sunny rai 2017-05-08 12:06:10

je cherchais ceci, et j'ai écrit un profond récursif 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" } })

10
répondu SylvainPV 2014-11-21 14:10:50

si vous voulez juste voir l'objet pour le débogage, vous pouvez utiliser

var o = {a:1, b:2} 
console.dir(o)
9
répondu PaulAndrewLang 2014-11-24 05:11:34

1.

JSON.stringify(o);

rubrique: {"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);

article: {a: 1, b:2}

7
répondu vacsati 2018-03-04 16:26:59
Les méthodes

JSON sont bien inférieures au moteur Gecko .tosource () primitive.

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

aussi, la réponse au-dessus de 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 "ExtJs JSON code source d'encodage" ) ne peut pas traiter les références circulaires et est incomplet. Le code ci-dessous montre ses limites (spoof) (corrigé pour gérer les tableaux et les objets sans contenu).

( lien direct vers le code in //forums.devshed.com/ ... /tosource-avec-des tableaux-dans-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
répondu Ekim 2017-05-23 11:47:29

comme firefox ne stringifie pas un objet comme 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
répondu Abdennour TOUMI 2013-07-29 13:17:06

regardez le jQuery-JSON plugin

à son centre, il utilise JSON.stringify mais retombe sur son propre analyseur si le navigateur ne l'implémente pas.

3
répondu Evan Plaice 2012-09-19 01:59:57

Si vous ne se soucient 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
répondu Anuraag Vaidya 2015-10-11 12:28:18
var o = {a:1, b:2};

o.toString=function(){
  return 'a='+this.a+', b='+this.b;
};

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

depuis Javascript v1.0 travaille partout (même) c'est une approche native et permet un look très costomisé de votre objet lors du débogage et de la production https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Utile exemple

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
répondu Alex 2016-07-28 16:55:57

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

npm install stringify-object`

puis:

const stringifyObject = require('stringify-object');
stringifyObject(myObject);
2
répondu Nicolas Zozol 2017-12-29 19:23:18

si vous utilisez le cadre javascript Dojo, il y a déjà une fonction build-in pour le faire: dojo.la méthode toJson() qui serait utilisé comme.

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

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

dojo.toJson(obj, true);

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

1
répondu Chris O'Connell 2011-09-21 21:15:21
/*
    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*/
    }

}
1
répondu sea-kg 2014-10-23 04:51:09

pour votre exemple, je pense console.log("Item:",o) serait plus facile. Mais, console.log("Item:" + o.toString) serait aussi travailler.

en utilisant la méthode numéro un utilise un bon dropdown dans la console, donc un long objet fonctionnerait bien.

1
répondu Fuzzyzilla 2015-09-13 22:11:10
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
répondu Mauro 2016-02-29 02:39:37

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
répondu Khushal Chheda 2016-06-10 10:44:46

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 itérer sur les objets aussi bien. Cela correspond à chaque entrée clé/valeur de sa représentation string:

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

et join() regroupent 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 ce ne va récursive par le biais de la Objet:

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

Comme nœud util.inspect() on va le faire:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'
0
répondu kwarnke 2017-10-12 15:32:53

si vous ne voulez pas jouer join() à 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
répondu Илья Индиго 2018-03-22 16:23:26

pour les objets non emboîtés:

Object.entries(o).map(x=>x.join(":")).join("\r\n")
0
répondu Alex Szücs 2018-08-20 15:50:57

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

si "nomvariable" est un objet et que vous utilisez l'opération de concaténation de chaîne vide, il donnera l'ennuyeux [object Object] , dans ce cas vous voulez probablement Gary C.'s énormément rétrogradé JSON.stringify réponse à la question postée, que vous pouvez lire sur le réseau de développeur de Mozilla à la lien dans réponse en haut .

0
répondu stackuser83 2018-09-12 23:07:02
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(',')+'}';
    }
-1
répondu Jimmy Anthony Bazan Solis 2015-04-23 14:46:32