1058

How can I convert a JavaScript object into a string?

Example:

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

Output:

Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
user680174
  • 10,581
  • 3
  • 13
  • 3
  • 7
    Convert to string to what purpose? You mean serialize so you can build the object later from the string? Or just for display? – Shadow The Vaccinated Wizard Apr 10 '11 at 15:40
  • 19
    The author is gone from years, but reading in mind, after years, I guess, the entry point for the problem was the console.log(obj), which display object with properties, while console.log('obj: '+obj) works disorientingly otherwise. – Danubian Sailor Oct 16 '13 at 13:45
  • 2
    simply can't apply add two object, If we can do so there would be no diff in value type and ref type. – Nishant Kumar Jun 08 '14 at 11:41
  • 12
    var o = {a:1, b:2}; console.log('Item: ' + JSON.stringify(o)) – Nishant Kumar Jun 08 '14 at 11:50
  • Maybe it's worth mentioning [jQuery's makeArray()](http://api.jquery.com/jquery.makearray/) – Nabil Kadimi Oct 24 '14 at 18:49
  • Firstly I convert functions with `String( func );`, then I convert the whole object with `JSON.stringify(obj);` - this way you get the functions' codes too... – jave.web Oct 28 '14 at 12:27
  • 23
    If it's for the console, I would recommend doing `console.log("Item", obj);`. No need for anything complicated. – soktinpk Nov 18 '14 at 23:55
  • You can create a custom `toString()` method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString – Timothy Zorn May 19 '15 at 20:34
  • 1
    For console, use console.log('text: %O', obj); the %O in the string literal will be replaced by the first additional parameter, assuming it is an object. – Martin Feb 15 '16 at 13:52
  • If the purpose is only for logging it to the console. you better use `console.dir(obj)` which prints the javascript object, and not only a string. (see https://developer.mozilla.org/de/docs/Web/API/Console/dir ) – EagleT Nov 25 '19 at 10:20
  • 1
    Does this answer your question? [How can I get the full object in Node.js's console.log(), rather than '\[Object\]'?](https://stackoverflow.com/questions/10729276/how-can-i-get-the-full-object-in-node-jss-console-log-rather-than-object) – Michael Freidgeim Feb 08 '20 at 03:46
  • See also https://stackoverflow.com/questions/11616630/how-can-i-print-a-circular-structure-in-a-json-like-format for circular objects. – grin Jul 02 '20 at 14:21

36 Answers36

1434

I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string. Most modern browsers support this method natively, but for those that don't, you can include a JS version:

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);
splash
  • 12,499
  • 1
  • 40
  • 64
Gary Chambers
  • 21,998
  • 4
  • 31
  • 28
  • 7
    For reference IE6 and 7 do not support this. IE6 isn't that big a deal because of very few users, and an active campaign to kill it ... but there are still quite a few IE7 users out there (depends on your user base). – MikeMurko Nov 21 '11 at 14:35
  • 33
    I get an "Uncaught TypeError: Converting circular structure to JSON". Even if there is a circular reference, i would still like to see a string-representation of my object. What can I do? – Pascal Klein Mar 21 '12 at 16:24
  • That 'JS version' link is broken, [here's a working one](https://github.com/douglascrockford/JSON-js/blob/master/json2.js), and [to its homepage](https://github.com/douglascrockford/JSON-js). – JDonner Sep 20 '12 at 21:21
  • 29
    This doesn't work if the object has a function property, eg: `foo: function () {...}`. – Brock Adams Sep 29 '12 at 14:54
  • 2
    Link to JSON library doesn't work if clicked from StackOverflow. Copy and paste it in the address bar. – f.ardelian Nov 03 '12 at 12:48
  • short and clean, also remember to add JSON2.js for some compatibility issue for older browsers – Allan Jikamu Mar 06 '13 at 03:11
  • Shout out that quotes " don't get escaped in the case of stringifying for saving to a database. – ericjam Feb 23 '15 at 21:42
  • 6
    You can use `JSON.stringify(obj, null, 2);` for a prettier output. – l.poellabauer Sep 28 '15 at 09:18
  • Given the passage of time, I don't think we will need to worry that much about 'IE6 and 7' anymore.. – wentjun Apr 17 '19 at 05:48
  • This doesn't always work. I'm using MutationObserver, and for each MutationRecords returned, JSON.stringify{mutationRecord} returns "{}" even though console.log{mutationRecord} shows the record is full of information. – John Smith Jul 30 '19 at 15:35
147

Use javascript String() function

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

or stringify()

JSON.stringify(yourobject)
Arsen Khachaturyan
  • 6,472
  • 4
  • 32
  • 36
Vikram Pote
  • 4,959
  • 4
  • 31
  • 34
93

Sure, to convert an object into a string, you either have to use your own method, such as:

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

Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604

or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.

FerCa
  • 1,917
  • 2
  • 14
  • 18
Brett Zamir
  • 12,481
  • 5
  • 45
  • 68
87

Keeping it simple with console, you can just use a comma instead of a +. The + will try to convert the object into a string, whereas the comma will display it separately in the console.

Example:

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

Output:

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

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log

Luke
  • 14,840
  • 10
  • 84
  • 92
  • Greate solution! But could u tell me what happens behind the scenes when you simply do this : `console.log(o)` ? Since if you try to log an object added to a string , it actually calls `toString()` on the object. – Gocy015 Nov 29 '16 at 03:29
  • 2
    `console.log` ultimately calls something called the `Printer` which the spec notes: "How the implementation prints args is up to the implementation" - meaning that every browser can do this different (see https://console.spec.whatwg.org/#printer). Firefox will display objects as a string, but colored nicely. Chrome will display the object as an interactive group that you can expand to see the properties. Give it a try! – Luke Nov 29 '16 at 16:53
  • 2
    Very nice trick and probably fine for modern web browers, but it isn't 100% reliable for all JS implementations. e.g. in Qt QML, which implements a JS engine, the output for `console.log('Item: ', o);` is still `Item: [object Object]`. – Paul Masri-Stone Mar 20 '17 at 10:48
  • Instead of `console.log` you can use `console.dir(o)` to print the javascript object instead to printig it as a string. In the developer tools this enables to open the object and check all properties, even arrays. (see: https://developer.mozilla.org/de/docs/Web/API/Console/dir ) – EagleT Nov 25 '19 at 10:22
40

EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.

toSource() is the function you are looking for which will write it out as JSON.

var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
FZs
  • 11,931
  • 11
  • 28
  • 41
Gazler
  • 78,438
  • 15
  • 263
  • 235
  • 7
    Though it is convenient for debugging in Firefox, `toSource()` does not work in IE. – Brett Zamir Apr 10 '11 at 15:42
  • 6
    `toSource()` is not a recognised standard, so cannot be guaranteed to be supported in all browsers. – Gary Chambers Apr 10 '11 at 15:46
  • 11
    Ahh, thank you for pointing that out. I will leave my answer here for others who are unaware of that. – Gazler Apr 10 '11 at 15:47
  • I wish I could upvote you more, as this is a brilliant solution for environments that have javascript (but the console log is inconvenient/impossible to access). – Zack Morris Nov 21 '14 at 21:25
  • You could provide a polypill to toSource: https://github.com/oliver-moran/toSource.js/blob/master/toSource.js – roland Apr 03 '16 at 14:29
  • @NeuroScr .toSource() does not rely on Node. It's in plain javascript. – Wyatt Ward Nov 03 '16 at 23:46
  • Does not work on chrome 71 macOS. JSON.stringify is the closest to what this does in the spec – jimmy jansen Jan 09 '19 at 09:50
  • 2
    this is simply not supported on any modern browser, how is this getting so many upvotes? am I missing anything? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toSource – Siraj Kakeh Nov 16 '20 at 22:11
34

One option:

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

o is printed as a string

Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:

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

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

nabn
  • 2,184
  • 21
  • 25
24

None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.

I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.

//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: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:

Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.

Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.

Houshalter
  • 1,918
  • 14
  • 20
21

If you're just outputting to the console, you can use console.log('string:', obj). Notice the comma.

  • This poses problems in scenarios where AJAX and deferred come to play - output from `console.log` is often displayed *after* AJAX has finished supplying the array with data in parallel, which leads to misleading results. In such cases cloning or serializing objects is the way to go: since we logged duplicated object, even when AJAX finishes its work, it will fill "old" data. – rr- Oct 15 '14 at 18:24
18

In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.

For example the following would convert all items in "value" to a string:

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

More details here:

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

Jake Drew
  • 1,902
  • 20
  • 27
15
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);
sunny rai
  • 427
  • 5
  • 6
12

I was looking for this, and wrote a deep recursive one with 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" } })

SylvainPV
  • 121
  • 1
  • 5
  • note that if you want to prevent infinite loops for objects with circular references, you may add `if(ndeep > MAX_DEPTH_LEVEL){ return '...'; }` in the function, with MAX_DEPTH_LEVEL being your chosen max number of object layers to dig in. – SylvainPV Mar 15 '15 at 16:43
11

If you just want to see the object for debugging, you can use

var o = {a:1, b:2} 
console.dir(o)
PaulAndrewLang
  • 379
  • 3
  • 4
11

There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:

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

I would prefer this as JSON.stringify() has certain limitations (e.g. with circular structures).

Christian Gawron
  • 815
  • 1
  • 6
  • 17
9

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);

Item: {a:1, b:2}

vacsati
  • 408
  • 4
  • 6
8

JSON methods are quite inferior to the Gecko engine .toSource() primitive.

See the SO article response for comparison tests.

Also, the answer above refers to http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html which, like JSON, (which the other article http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json uses via "ExtJs JSON encode source code") cannot handle circular references and is incomplete. The code below shows it's (spoof's) limitations (corrected to handle arrays and objects without content).

(direct link to code in //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'));

which displays:

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")]

and

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")]

and

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]
Community
  • 1
  • 1
Ekim
  • 353
  • 2
  • 4
7

It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:

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

As firefox does not stringify some object as screen object ; if you want to have the same result such as : 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(',')+'}';
}
Abdennour TOUMI
  • 64,884
  • 28
  • 201
  • 207
5

If you only care about strings, objects, and arrays:

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;
    }
Anuraag Vaidya
  • 787
  • 7
  • 15
5

stringify-object is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-object

npm install stringify-object

then:

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

Obviously it's interesting only if you have circular object that would fail with JSON.stringify();

Nicolas Zozol
  • 6,609
  • 1
  • 46
  • 66
5

For non-nested objects:

Object.entries(o).map(x=>x.join(":")).join("\r\n")
Alex Szücs
  • 167
  • 2
  • 7
4

Take a look at the jQuery-JSON plugin

At its core, it uses JSON.stringify but falls back to its own parser if the browser doesn't implement it.

skierpage
  • 2,214
  • 19
  • 17
Evan Plaice
  • 13,310
  • 4
  • 70
  • 94
2
var o = {a:1, b:2};

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

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

Since Javascript v1.0 works everywhere (even IE) this is a native approach and allows for a very costomised look of your object while debugging and in production https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Usefull example

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

Also, as a 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
Alex
  • 29
  • 1
2

If you can use lodash you can do it this way:

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

With lodash map() you can iterate over Objects as well. This maps every key/value entry to its string representation:

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

And join() put the array entries together.

If you can use ES6 Template String, this works also:

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

Please note this do not goes recursive through the Object:

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

Like node's util.inspect() will do:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'
kwarnke
  • 1,078
  • 1
  • 11
  • 9
2

Circular References

By using below replacer we can produce less redundant JSON - if source object contains multi-references to some object, or contains circular references - then we reference it by special path-string (similar to JSONPath) - we use it as follows

let s = JSON.stringify(obj, refReplacer());

function refReplacer() {
  let m = new Map(), v= new Map(), init = null;

  return function(field, value) {
    let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field); 
    let isComplex= value===Object(value)
    
    if (isComplex) m.set(value, p);  
    
    let pp = v.get(value)||'';
    let path = p.replace(/undefined\.\.?/,'');
    let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
    
    !init ? (init=value) : (val===init ? val="#REF:$" : 0);
    if(!pp && isComplex) v.set(value, path);
   
    return val;
  }
}




// ---------------
// TEST
// ---------------

// gen obj with duplicate references
let a = { a1: 1, a2: 2 };
let b = { b1: 3, b2: "4" };
let obj = { o1: { o2:  a  }, b, a }; // duplicate reference
a.a3 = [1,2,b];                      // circular reference
b.b3 = a;                            // circular reference


let s = JSON.stringify(obj, refReplacer(), 4);

console.log(s);

BONUS: and here is inverse function of such serialisation

function parseRefJSON(json) {
  let objToPath = new Map();
  let pathToObj = new Map();
  let o = JSON.parse(json);
  
  let traverse = (parent, field) => {
    let obj = parent;
    let path = '#REF:$';

    if (field !== undefined) {
      obj = parent[field];
      path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
    }

    objToPath.set(obj, path);
    pathToObj.set(path, obj);
    
    let ref = pathToObj.get(obj);
    if (ref) parent[field] = ref;

    for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
  }
  
  traverse(o);
  return o;
}



// ------------
// TEST
// ------------

let s = `{
    "o1": {
        "o2": {
            "a1": 1,
            "a2": 2,
            "a3": [
                1,
                2,
                {
                    "b1": 3,
                    "b2": "4",
                    "b3": "#REF:$.o1.o2"
                }
            ]
        }
    },
    "b": "#REF:$.o1.o2.a3[2]",
    "a": "#REF:$.o1.o2"
}`;

console.log('Open Chrome console to see nested fields:');
let obj = parseRefJSON(s);

console.log(obj);
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
2

maybe you are looking for

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"
Shashwat Gupta
  • 3,139
  • 23
  • 21
1
/*
    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;
};

example to use:

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

}
sea-kg
  • 179
  • 1
  • 3
1

For your example, I think console.log("Item:",o) would be easiest. But, console.log("Item:" + o.toString) would also work.

Using method number one uses a nice dropdown in the console, so a long object would work nicely.

Fuzzyzilla
  • 366
  • 5
  • 13
1
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)+"}";
}
Mauro
  • 11
  • 1
1

I hope this example will help for all those who all are working on array of objects

var data_array = [{
                    "id": "0",
                    "store": "ABC"
                },{
                    "id":"1",
                    "store":"XYZ"
                }];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
Sender
  • 6,106
  • 11
  • 42
  • 59
1

If you wont aplay join() to Object.

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

I had need to make a more configurable version of JSON.stringify as I had to add comments and know the JSON path:

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);
Dominic
  • 48,717
  • 14
  • 109
  • 126
1

If you are using the Dojo javascript framework then there is already a build in function to do this: dojo.toJson() which would be used like so.

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

which will return a string. If you want to convert the object to json data then add a second parameter of true.

dojo.toJson(obj, true);

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

Chris O'Connell
  • 365
  • 2
  • 11
0

If you want a minimalist method of converting a variable to a string for an inline expression type situation, ''+variablename is the best I have golfed.

If 'variablename' is an object and you use the empty string concatenation operation, it will give the annoying [object Object], in which case you probably want Gary C.'s enormously upvoted JSON.stringify answer to the posted question, which you can read about on Mozilla's Developer Network at the link in that answer at the top.

stackuser83
  • 1,402
  • 1
  • 18
  • 37
0

If all you want is to simply get a string output, then this should work: String(object)

Moe
  • 111
  • 1
  • 10
0

add on ---

JSON.stringify(obj) is nice, but it will convert to json string object. sometimes we will need the string of it, like when posting it in body for WCF http post and recieving as a string.

in order of this we should reuse the stringify() as following:

let obj = {id:1, name:'cherry'};
let jsonObj = JSON.stringify(doc); //json object string
let strObj = JSON.stringify(jsonObj); //json object string wrapped with string
chaya D
  • 79
  • 1
  • 11
-1
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(',')+'}';
    }
xlecoustillier
  • 15,451
  • 14
  • 56
  • 79