将对象转换为字符串

Converting an object to a string

提问人:user680174 提问时间:4/10/2011 最后编辑:Kamil Kiełczewskiuser680174 更新时间:9/3/2023 访问量:2270605

问:

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

例:

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

输出:

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

JavaScript 对象 序列化 到 String

评论

7赞 Shadow Wizard Is Sad And Angry 4/10/2011
转换为字符串的目的是什么?您的意思是序列化,以便稍后可以从字符串构建对象?还是只是为了展示?
22赞 Danubian Sailor 10/16/2013
作者已经离开了多年,但读起来,多年后,我猜,问题的入口点是console.log(obj),它显示带有属性的对象,而console.log('obj: '+obj)则以其他方式迷失方向。
2赞 Nishant Kumar 6/8/2014
根本无法应用添加两个对象,如果我们可以这样做,则值类型和引用类型不会有差异。
13赞 Nishant Kumar 6/8/2014
变量 o = {a:1, b:2};console.log('项目: ' + JSON.stringify(o))
30赞 soktinpk 11/19/2014
如果是控制台,我建议做.不需要任何复杂的东西。console.log("Item", obj);

答:

39赞 Gazler 4/10/2011 #1

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

toSource() 是您要查找的函数,它会将其写成 JSON。

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

评论

7赞 Brett Zamir 4/10/2011
虽然在Firefox中调试很方便,但在IE中不起作用。toSource()
8赞 Gary Chambers 4/10/2011
toSource()不是公认的标准,因此不能保证在所有浏览器中都受支持。
11赞 Gazler 4/10/2011
啊,谢谢你指出这一点。我将把我的答案留给其他不知道这一点的人。
0赞 Zack Morris 11/22/2014
我希望我能给你更多的投票,因为对于具有 javascript 的环境来说,这是一个绝妙的解决方案(但控制台日志不方便/无法访问)。
4赞 Siraj Kakeh 11/17/2020
这在任何现代浏览器上都不受支持,这如何获得如此多的赞成票?我错过了什么吗?developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/......
1618赞 Gary Chambers 4/10/2011 #2

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

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

大多数现代浏览器本身都支持此方法,但对于不支持此方法的浏览器,您可以包含 JS 版本

评论

7赞 MikeMurko 11/21/2011
作为参考,IE6 和 7 不支持此功能。IE6 没什么大不了的,因为用户很少,而且有一个积极的运动来杀死它......但仍然有相当多的 IE7 用户(取决于您的用户群)。
39赞 Pascal Klein 3/22/2012
我收到一个“Uncaught TypeError: Converting circular structure to JSON”。即使有一个循环引用,我仍然希望看到我的对象的字符串表示。我能做些什么?
32赞 Brock Adams 9/29/2012
如果对象具有函数属性,则此操作不起作用,例如:.foo: function () {...}
2赞 f.ardelian 11/3/2012
如果从 StackOverflow 单击,则链接到 JSON 库不起作用。将其复制并粘贴到地址栏中。
15赞 l.poellabauer 9/28/2015
您可以用于更漂亮的输出。JSON.stringify(obj, null, 2);
106赞 Brett Zamir 4/10/2011 #3

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

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`;
    }, '');
}
8赞 Ekim 4/20/2011 #4

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编码源代码”使用)无法处理循环引用并且不完整。下面的代码显示了它的(欺骗)限制(更正为处理没有内容的数组和对象)。

(直接链接到 //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'));

其中显示:

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

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]
4赞 Evan Plaice 5/2/2012 #5

看看 jQuery-JSON 插件

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

18赞 Jake Drew 7/11/2013 #6

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

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

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

更多细节在这里:

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

评论

0赞 John Magnolia 7/25/2013
var my_string = ''+value+'';
2赞 Tillito 9/15/2013
对我有用。我更喜欢这个解决方案,因为我不会使用插件来完成如此简单的任务。
5赞 Abdennour TOUMI 7/29/2013 #7

由于 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(',')+'}';
}
25赞 Houshalter 8/22/2013 #8

这里没有一个解决方案对我有用。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”,并且不会添加过多的逗号。

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

评论

0赞 dacopenhagen 8/30/2014
你缺少一些'}
2赞 NiCk Newman 7/29/2015
非常好的代码,但是每个对象/数组的末尾都有一个尾随。,
22赞 Alexandre R. Janini 8/14/2014 #9

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

评论

0赞 rr- 10/16/2014
这在 AJAX 和延迟发挥作用的情况下会带来问题 - 输出通常在 AJAX 完成并行向数组提供数据显示,这会导致误导性结果。在这种情况下,克隆或序列化对象是要走的路:因为我们记录了重复的对象,即使 AJAX 完成了它的工作,它也会填充“旧”数据。console.log
1赞 sea-kg 9/18/2014 #10
/*
    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*/
    }

}

评论

1赞 estemendoza 10/22/2014
这将是一个很好的解释,并解释了代码的作用以及如何使用它的示例。谢谢
15赞 SylvainPV 11/19/2014 #11

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

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

评论

0赞 SylvainPV 3/16/2015
请注意,如果要防止具有循环引用的对象出现无限循环,可以添加该函数,MAX_DEPTH_LEVEL 是您选择的要挖掘的最大对象层数。if(ndeep > MAX_DEPTH_LEVEL){ return '...'; }
11赞 PaulAndrewLang 11/24/2014 #12

如果只想查看要调试的对象,可以使用

var o = {a:1, b:2} 
console.dir(o)
106赞 Luke 1/8/2015 #13

简单起见,您可以只使用逗号而不是 .将尝试将对象转换为字符串,而逗号将在控制台中单独显示它。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/docs/Web/API/Console.log

评论

0赞 Gocy015 11/29/2016
Greate解决方案!但是你能告诉我当你简单地这样做时,幕后会发生什么:?因为如果你尝试记录一个添加到字符串中的对象,它实际上会调用该对象。console.log(o)toString()
3赞 Luke 11/30/2016
console.log最终调用了规范指出的称为 the 的东西:“实现如何打印参数取决于实现”——这意味着每个浏览器都可以以不同的方式做到这一点(参见 console.spec.whatwg.org/#printer)。Firefox 会将对象显示为字符串,但颜色很好。Chrome 会将对象显示为一个交互式组,您可以展开该组以查看属性。试一试吧!Printer
2赞 Paul Masri-Stone 3/20/2017
非常好的技巧,对于现代网络浏览器来说可能很好,但对于所有 JS 实现来说,它并不是 100% 可靠的。例如,在实现JS引擎的Qt QML中,输出仍然是。console.log('Item: ', o);Item: [object Object]
0赞 EagleT 11/25/2019
而不是你可以用来打印javascript对象,而是把它打印成一个字符串。在开发人员工具中,这可以打开对象并检查所有属性,甚至是数组。(参见:developer.mozilla.org/de/docs/Web/API/Console/dirconsole.logconsole.dir(o) )
33赞 nabn 6/19/2015 #14

一种选择

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

o is printed as a string

另一种选择(正如 soktinpk 在评论中指出的那样),更适合控制台调试 IMO:

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

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

1赞 Fuzzyzilla 9/14/2015 #15

对于你的例子,我认为是最简单的。但是,也可以。console.log("Item:",o)console.log("Item:" + o.toString)

使用方法第一种在控制台中使用一个不错的下拉列表,因此长对象可以很好地工作。

5赞 Anuraag Vaidya 10/11/2015 #16

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

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;
    }
2赞 Mauro 2/29/2016 #17
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)+"}";
}
173赞 Vikram Pote 4/15/2016 #18

使用 javascript String() 函数

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

或者 stringify()

JSON.stringify(yourobject)

评论

39赞 Anti Veeranna 5/3/2016
var foo = {bar: 1};字符串(foo);-> “[object 对象]”
1赞 Vikram Pote 5/3/2016
var foo = {bar: 1};字符串(foo['bar']);->“1”
4赞 Vikram Pote 5/3/2016
如果你想把整个对象作为字符串,请使用 JSON.stringify(foo)
2赞 techie_28 5/18/2016
@VikramPote 我认为没有办法将对象检索到真实状态。"[object Object]"
0赞 techie_28 5/18/2016
JSON.stringify 并不适合所有情况,例如输入字段的 jQuery 引用对象,如按钮等。
1赞 Khushal Chheda 6/10/2016 #19

我希望这个例子能帮助所有那些都在处理对象数组的人

var data_array = [{
                    "id": "0",
                    "store": "ABC"
                },{
                    "id":"1",
                    "store":"XYZ"
                }];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
2赞 Alex 7/29/2016 #20
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
15赞 sunny rai 5/8/2017 #21
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);
3赞 kwarnke 10/12/2017 #22

如果你能使用 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 } }'
7赞 Nicolas Zozol 12/30/2017 #23

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

npm install stringify-object

然后:

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

显然,只有当你有圆形物体时,它才有趣JSON.stringify();

评论

1赞 Zelphir Kaltstahl 10/12/2018
为什么有人会使用 NPM 模块来做这样的事情,这可以通过普通 JS 中的单行来实现?这个答案需要详细说明为什么有人会这样做。
0赞 Nicolas Zozol 10/15/2018
通常,库在边缘情况下会有所帮助。我用它来处理循环引用。
1赞 Zelphir Kaltstahl 10/15/2018
这更有意义,添加了关于圆形物体的注释,删除了我的反对票。
0赞 Rzassar 3/16/2023
@ZelphirKaltstahl 仅仅是因为结果,而我需要。注意 .JSON.stringify(obj){"key":"value"}{key:"value"}key
10赞 vacsati 3/5/2018 #24

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}

评论

3赞 Harun Diluka Heshan 3/5/2018
如果您考虑添加有关答案的更多详细信息,那就更好了。
1赞 Илья Индиго 3/23/2018 #25

如果你不愿意,请将 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(',');
9赞 Alex Szücs 8/20/2018 #26

对于非嵌套对象:

Object.entries(o).map(x=>x.join(":")).join("\r\n")
14赞 Christian Gawron 2/13/2019 #27

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

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

我更喜欢这个,因为它有一定的局限性(例如圆形结构)。JSON.stringify()

10赞 Gleb Dolzikov 4/25/2019 #28

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

JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return String(val);
    }
    return val;
  });
2赞 Kamil Kiełczewski 5/14/2020 #29

循环引用

通过使用下面的替换器,我们可以生成更少的冗余 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]=='[' ? '$':'$.'}${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);

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

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

5赞 Shashwat Gupta 9/10/2020 #30

也许你正在寻找

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"