如何将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] //不知道里面有什么:(
当前回答
如果你只是输出到控制台,你可以使用console.log('string:', obj)。注意逗号。
其他回答
这里没有一个解决方案对我有效。JSON。stringify似乎是很多人所说的,但它削减了函数,并且在我测试时尝试的一些对象和数组似乎很坏。
我做了自己的解决方案,至少在Chrome中工作。把它贴在这里,这样任何在谷歌上看到的人都能找到它。
//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',也没有添加过多的逗号。
使用它在你自己的风险,因为我没有验证它在所有。请随意提出任何额外的改进意见。
看看jQuery-JSON插件
它的核心是使用JSON。但是如果浏览器没有实现它,它就会退回到自己的解析器。
如果你只是输出到控制台,你可以使用console.log('string:', obj)。注意逗号。
我需要制作一个更可配置的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);
下面是一些简单的解决方案。
它只对字符串显示"",对数字和函数/方法不显示""(如果方法是这样写的):
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