Converting an object to a string

后端 未结 30 1827
北荒
北荒 2020-11-22 03:29

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:

相关标签:
30条回答
  • 2020-11-22 04:18

    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.

    0 讨论(0)
  • 2020-11-22 04:20

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

    0 讨论(0)
  • 2020-11-22 04:21

    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(',')+'}';
    }
    
    0 讨论(0)
  • 2020-11-22 04:21

    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"]));
    
    0 讨论(0)
  • 2020-11-22 04:22

    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

    0 讨论(0)
  • 2020-11-22 04:24

    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;
      });
    
    0 讨论(0)
提交回复
热议问题