如何将 JavaScript 对象转换为字符串?
示例:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象 { a=1, b=2} // 非常良好易读 :)
条目: [object Object] // 不知道里面是什么 :(
如何将 JavaScript 对象转换为字符串?
示例:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象 { a=1, b=2} // 非常良好易读 :)
条目: [object Object] // 不知道里面是什么 :(
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);
实际上,现有答案中缺少一种简单的选择(适用于最近版本的浏览器和Node.js):
console.log('Item: %o', o);
我更喜欢这样,因为JSON.stringify()
有一定的限制(例如,对于循环结构)。
如果您只想为调试查看对象,您可以使用
var o = {a:1, b:2}
console.dir(o)
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}JSON似乎接受第二个参数,可以帮助函数-replacer,这样以最优雅的方式解决了转换问题:
JSON.stringify(object, (key, val) => {
if (typeof val === 'function') {
return String(val);
}
return val;
});
对于非嵌套的对象:
Object.entries(o).map(x=>x.join(":")).join("\r\n")
与Gecko引擎的.toSource()原始方法相比,JSON方法相当逊色。
有关比较测试,请参见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 encode source code”使用)一样,不能处理循环引用并且不完整。下面的代码显示了它(欺骗)的局限性(已更正以处理没有内容的数组和对象)。
(直接链接到代码在//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]
stringify-object
是由 Yeoman 团队开发的一个不错的 npm 库:https://www.npmjs.com/package/stringify-object
npm install stringify-object
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
JSON.stringify();
而失败的循环对象时,这才是有趣的。JSON.stringify(obj)
生成的结果是{"key":"value"}
,而我需要的是{key:"value"}
。请注意key
周围引号的位置。 - Rzassar如果你只关心字符串、对象和数组:
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;
}
由于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(',')+'}';
}
console.log("Item", obj);
。不需要过于复杂的代码。 - soktinpk