如何将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] //不知道里面有什么:(
当前回答
如果您正在使用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
其他回答
使用javascript String()函数
String(yourobject); //returns [object Object]
或stringify ()
JSON.stringify(yourobject)
我需要制作一个更可配置的JSON版本。stringify,因为我必须添加注释和知道JSON路径:
const someObj = { a: { nested: { value: 'apple', }, sibling: 'peanut' }, b: { languages: ['en', 'de', 'fr'], c: { nice: 'heh' } }, c: 'butter', d: function () {} }; function* objIter(obj, indent = ' ', depth = 0, path = '') { const t = indent.repeat(depth); const t1 = indent.repeat(depth + 1); const v = v => JSON.stringify(v); yield { type: Array.isArray(obj) ? 'OPEN_ARR' : 'OPEN_OBJ', indent, depth }; const keys = Object.keys(obj); for (let i = 0, l = keys.length; i < l; i++) { const key = keys[i]; const prop = obj[key]; const nextPath = !path && key || `${path}.${key}`; if (typeof prop !== 'object') { yield { type: isNaN(key) ? 'VAL' : 'ARR_VAL', key, prop, indent, depth, path: nextPath }; } else { yield { type: 'OBJ_KEY', key, indent, depth, path: nextPath }; yield* objIter(prop, indent, depth + 1, nextPath); } } yield { type: Array.isArray(obj) ? 'CLOSE_ARR' : 'CLOSE_OBJ', indent, depth }; } const iterMap = (it, mapFn) => { const arr = []; for (const x of it) { arr.push(mapFn(x)) } return arr; } const objToStr = obj => iterMap(objIter(obj), ({ type, key, prop, indent, depth, path }) => { const t = indent.repeat(depth); const t1 = indent.repeat(depth + 1); const v = v => JSON.stringify(v); switch (type) { case 'OPEN_ARR': return '[\n'; case 'OPEN_OBJ': return '{\n'; case 'VAL': return `${t1}// ${path}\n${t1}${v(key)}: ${v(prop)},\n`; case 'ARR_VAL': return `${t1}// ${path}\n${t1}${v(prop)},\n`; case 'OBJ_KEY': return `${t1}// ${path}\n${t1}${v(key)}: `; case 'CLOSE_ARR': case 'CLOSE_OBJ': return `${t}${type === 'CLOSE_ARR' ? ']' : '}'}${depth ? ',' : ';'}\n`; default: throw new Error('Unknown type:', type); } }).join(''); const s = objToStr(someObj); console.log(s);
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
由于firefox没有将某些对象stringify为屏幕对象;如果你想有相同的结果,如: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(',')+'}';
}
如果您正在使用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