将对象转换为字符串

发布于 2024-10-31 17:12:54 字数 253 浏览 1 评论 0原文

如何将 JavaScript 对象转换为字符串?

示例:

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

输出:

Object { a=1, b=2} // 非常好的可读输出:)
Item: [object Object] // 不知道里面有什么:(

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 :(

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

彩扇题诗 2024-11-07 17:12:55

JSON 方法远不如 Gecko 引擎 .toSource() 原语。

请参阅 SO 文章响应 用于比较测试。

另外,上面的答案http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html ,就像 JSON 一样,(另一篇文章 http://www.davidpirek。 com/blog/object-to-string-how-to-deserialize-json 通过 "ExtJs JSON 编码源代码") 无法处理循环引用并且不完整。下面的代码显示了它的(欺骗)限制(已更正以处理没有内容的数组和对象)。

(直接链接到论坛中的代码。 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'));

显示:

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

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

devshed.com/ ... /tosource-with-arrays -

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]

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]
玩物 2024-11-07 17:12:55

stringify-object 是 yeoman 团队制作的一个很好的 npm 库:https: //www.npmjs.com/package/stringify-object

npm install stringify-object

然后:

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

显然,只有当你有一个会因 JSON.stringify(); 失败的循环对象时,它才有意义

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

奈何桥上唱咆哮 2024-11-07 17:12:55

由于 Firefox 不会将某些对象字符串化为屏幕对象;如果您想获得相同的结果,例如: 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(',')+'}';
}

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(',')+'}';
}
木格 2024-11-07 17:12:55

如果您只关心字符串、对象和数组:

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

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;
    }
江挽川 2024-11-07 17:12:55

也许你正在寻找

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"

maybe you are looking for

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"
客…行舟 2024-11-07 17:12:55

查看 jQuery-JSON 插件

核心,它使用 JSON.stringify 但如果浏览器没有实现它,则回退到它自己的解析器。

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.

深爱成瘾 2024-11-07 17:12:55

如果您可以使用 lodash,您可以这样做:

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

使用 lodash map() 您也可以迭代对象。
这会将每个键/值条目映射到其字符串表示形式:

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

并且 join() 将数组条目放在一起。

如果您可以使用 ES6 模板字符串,这也适用:

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

请注意,这不会通过对象递归:

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

就像 node 的 util.inspect() 将执行以下操作:

> util.inspect(o)
'{ a: 1, b: { c: 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 } }'
蒲公英的约定 2024-11-07 17:12:55
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)+"}";
}
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)+"}";
}
甜嗑 2024-11-07 17:12:55
var o = {a:1, b:2};

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

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

由于 Javascript v1.0 可以在任何地方使用(甚至是 IE)
这是一种本机方法,允许在调试和生产过程中使对象具有非常定制的外观
https://developer.mozilla.org/en/docs /Web/JavaScript/Reference/Global_Objects/Object/toString

有用的示例

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

另外,作为奖励

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
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
垂暮老矣 2024-11-07 17:12:55

循环引用

通过使用下面的 replacer< /strong> 我们可以生成更少冗余的 JSON - 如果源对象包含对某个对象的多重引用,或者包含循环引用 - 那么我们通过特殊的路径字符串引用它(类似于 JSONPath) - 我们按如下方式使用它

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]=='[' ? '

奖励:这是此类序列化的反函数

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:

:'$.'}${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);

奖励:这是此类序列化的反函数


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

:'$.'}${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);

奖励:这是此类序列化的反函数

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]=='[' ? '

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:

:'$.'}${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


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

:'$.'}${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

鸢与 2024-11-07 17:12:55
/*
    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;
};

使用示例:

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

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

}
不…忘初心 2024-11-07 17:12:55

对于你的例子,我认为
console.log("项目:",o)
会是最简单的。但,
console.log("Item:" + o.toString)
也会起作用。

使用方法一会在控制台中使用一个很好的下拉菜单,因此长对象可以很好地工作。

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.

丶情人眼里出诗心の 2024-11-07 17:12:55

我希望这个例子对所有处理对象数组的人有所帮助

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

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"]));
风月客 2024-11-07 17:12:55

如果您不使用 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(',');

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(',');
夏日落 2024-11-07 17:12:54

我建议使用 JSON.stringify< /code>,它将对象中的变量集转换为 JSON 字符串。

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

大多数现代浏览器本身支持此方法,但对于那些不支持此方法的浏览器,您可以添加 JS 版本

I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string.

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

Most modern browsers support this method natively, but for those that don't, you can include a JS version.

白云悠悠 2024-11-07 17:12:54

使用 javascript String() 函数

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

stringify()

JSON.stringify(yourobject)

Use javascript String() function

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

or stringify()

JSON.stringify(yourobject)
橪书 2024-11-07 17:12:54

为了让 console 保持简单,您可以只使用逗号而不是 ++ 将尝试将对象转换为字符串,而逗号将在控制台中单独显示它。

示例:

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

输出:

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

参考:https://developer.mozilla.org/en-US/文档/Web/API/Console.log

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

无名指的心愿 2024-11-07 17:12:54

当然,要将对象转换为字符串,你要么必须使用自己的方法,例如:

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

实际上,上面只是展示了一般方法;您可能希望使用类似 http://phpjs.org/functions/var_export:578http://phpjs.org/functions/var_dump:604

或者,如果您不使用方法(作为对象的属性),您也许可以使用新标准(但在旧版浏览器中未实现,尽管您也可以找到一个实用程序来帮助它们),JSON.stringify()。但同样,如果对象使用不可序列化为 JSON 的函数或其他属性,则该方法将不起作用。

更新

更现代的解决方案是:

function objToString (obj) {
    let str = '';
    for (const [p, val] of Object.entries(obj)) {
        str += `${p}::${val}\n`;
    }
    return str;
}

或者:

function objToString (obj) {
    return Object.entries(obj).reduce((str, [p, val]) => {
        return `${str}${p}::${val}\n`;
    }, '');
}

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 (Object.prototype.hasOwnProperty.call(obj, 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.

Update:

A more modern solution would be:

function objToString (obj) {
    let str = '';
    for (const [p, val] of Object.entries(obj)) {
        str += `${p}::${val}\n`;
    }
    return str;
}

or:

function objToString (obj) {
    return Object.entries(obj).reduce((str, [p, val]) => {
        return `${str}${p}::${val}\n`;
    }, '');
}
嘿哥们儿 2024-11-07 17:12:54

编辑 不要使用此答案,因为它仅适用于某些版本的 Firefox。没有其他浏览器支持它。使用Gary Chambers解决方案。

toSource() 是您正在寻找的函数,它将把它写成 JSON。

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

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());
口干舌燥 2024-11-07 17:12:54

一个选项

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

o is print as a string

另一个选项(正如评论中指出的soktinpk),并且更适合控制台调试IMO:

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

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

命硬 2024-11-07 17:12:54

这里的解决方案都不适合我。 JSON.stringify 似乎是很多人所说的,但它删除了函数,并且对于我在测试它时尝试的某些对象和数组来说似乎相当糟糕。

我制作了自己的解决方案,至少可以在 Chrome 中使用。将其发布在这里,以便任何在 Google 上查找此内容的人都可以找到它。

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

编辑:我知道这段代码可以改进,但只是从来没有抽出时间去做。用户 andrey 在此处建议进行改进,并发表评论:

这里稍微修改一下代码,可以处理“null”和“undefined”,并且不要添加过多的逗号。

使用它需要您自担风险,因为我根本没有验证过它。请随时以评论的形式提出任何其他改进建议。

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.

稀香 2024-11-07 17:12:54

如果您只是输出到控制台,则可以使用console.log('string:', obj)。注意逗号

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

南城旧梦 2024-11-07 17:12:54

如果您知道该对象只是布尔值、日期、字符串、数字等,则 javascript String() 函数可以正常工作。我最近发现这在处理来自 jquery 的 $.each 函数的值时很有用。

例如,以下内容会将“value”中的所有项目转换为字符串:

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

此处有更多详细信息:

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

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

失与倦" 2024-11-07 17:12:54

我一直在寻找这个,并写了一个带有缩进的深度递归:

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

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

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

浅语花开 2024-11-07 17:12:54
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);
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);
愚人国度 2024-11-07 17:12:54

实际上,现有答案中缺少一个简单的选项(对于最近的浏览器和 Node.js):

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

我更喜欢这个,因为 JSON.stringify() 有一定的限制(例如,具有循环结构)。

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

惟欲睡 2024-11-07 17:12:54

如果您只想查看对象以进行调试,您可以使用

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

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

var o = {a:1, b:2} 
console.dir(o)
雨夜星沙 2024-11-07 17:12:54

1.

JSON.stringify(o);

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

项目:{a:1, b:2}

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}

旧城烟雨 2024-11-07 17:12:54

看来 JSON 接受第二个可以帮助函数的参数 - replacer,这解决了以最优雅的方式转换的问题:

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

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;
  });
悲欢浪云 2024-11-07 17:12:54

对于非嵌套对象:

Object.entries(o).map(x=>x.join(":")).join("\r\n")

For non-nested objects:

Object.entries(o).map(x=>x.join(":")).join("\r\n")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文