如何将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"]));
如果您正在使用Dojo javascript框架,那么已经有一个内置函数来完成此工作:Dojo . tojson(),它将像这样使用。
var obj = {
name: 'myObj'
};
dojo.toJson(obj);
它将返回一个字符串。如果要将对象转换为json数据,则添加第二个参数true。
dojo.toJson(obj, true);
http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson
在检查最后一项时,使用reduce来更改(key,value)元组之间的分隔符sep的修改方法:
/**
* Object to string
* @param {*} obj
* @param {*} k_sep keys separator
* @param {*} v_sep values separator
* @returns
*/
var objectToString: function (obj, k_sep = '=', v_sep = ',') {
const entries = Object.entries(obj);
return entries.reduce((str, [p, val], counter) => {
if (counter < entries.length - 1) {
return `${str}${p}${k_sep}${val}${v_sep}`;
} else {
return `${str}${p}${k_sep}${val}`;
}
}, '');
}
/** * Object to string * @param {*} obj * @param {*} k_sep keys separator * @param {*} v_sep values separator * @returns */ var objectToString = function(obj, k_sep = '=', v_sep = ',') { const entries = Object.entries(obj); return entries.reduce((str, [p, val], counter) => { if (counter < entries.length - 1) { return `${str}${p}${k_sep}${val}${v_sep}`; } else { return `${str}${p}${k_sep}${val}`; } }, ''); } console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, ':', ",")) console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, '=', ","))
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
实际上,现有的答案中缺少一个简单的选项(适用于最近的浏览器和Node.js):
console.log('Item: %o', o);
我更喜欢这样做,因为JSON.stringify()有一定的限制(例如循环结构)。