如何将JavaScript对象转换为字符串?
例子:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(
如何将JavaScript对象转换为字符串?
例子:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(
当前回答
循环引用
通过使用下面的替换器,我们可以产生更少冗余的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);
其他回答
我希望这个例子将有助于所有那些谁都在数组对象的工作
var data_array = [{
"id": "0",
"store": "ABC"
},{
"id":"1",
"store":"XYZ"
}];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
对于非嵌套对象:
Object.entries(o).map(x=>x.join(":")).join("\r\n")
下面是一些简单的解决方案。
它只对字符串显示"",对数字和函数/方法不显示""(如果方法是这样写的):
let obj = {
name: "Philips TV",
price: 2500,
somemethod: function() {return "Hi there"}
};
let readableobj = '{ ';
for(key in obj) {
readableobj +=
(typeof obj[key] === "string")? `${key}: "${obj[key]}", ` : `${key}: ${obj[key]}, `;
}
readableobj += '}';
console.log('obj', readableobj); // obj { name: "Philips TV", price: 42, somemethod: function() {return "Hi there"}, }
这个解决方案使用尾随逗号(自ECMAScript 5起是合法的-请参阅MDN中的参考)。
代码基于'for in'循环的最简单形式:
let obj = {key: "value"};
for(key in obj) {
return "The property " + key + " with value " + obj[key];
}
注意:它甚至适用于这种方法符号:
let obj = {
name: "Philips TV",
price: 2500,
somemethod() {return "Hi there"}
};
将结果显示为
obj { name: "Philips TV", price: 42, somemethod: somemethod() {return "Hi there"}, }
甚至对于箭头函数符号
let obj = {
name: "Philips TV",
price: 2500,
somemethod: () => {return "Hi there"}
};
将结果显示为
obj { name: "Philips TV", price: 42, somemethod: () => {return "Hi there"}, }
因此,你可以以一种可接受的格式显示一个对象,即使它里面有三种形式的方法符号,就像这样:
let obj = {
name: "Philips TV",
price: 2500,
method1: function() {return "Hi there"},
method2() {return "Hi there"},
method3: () => {return "Hi there"}
};
有人可能会看到,即使是第二种格式method2() {return "Hi there"},通过复制它的标识符,最终也会显示为一个对键:值
// method2: method2() {return "Hi there"}
最后,true / false、undefined、null的处理方式与数字和函数相同(在最终格式中没有显示“”),因为它们也不是字符串。
重要的是:
JSON.stringify()销毁原始对象,这意味着方法丢失,并且不会显示在由它创建的最终字符串中。
因此,我们可能不应该接受涉及它的使用的解决方案。
console.log('obj', JSON.stringify(obj)); // obj {"name":"Philips TV","price":2500} // which is NOT acceptable
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(',')+'}';
}
如果你只关心字符串、对象和数组:
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;
}