如何将JavaScript对象转换为字符串?

例子:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

输出:

对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(


当前回答

一个选项:

console.log('Item: ' + JSON.stringify(o));

另一个选项(正如soktinpk在评论中指出的那样),更适合控制台调试IMO:

console.log('Item: ', o);

其他回答

如果你不播放join()到对象。

const obj = {one:1, two:2, three:3};
let arr = [];
for(let p in obj)
    arr.push(obj[p]);
const str = arr.join(',');
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(',')+'}';
    }

我需要制作一个更可配置的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);

看看jQuery-JSON插件

它的核心是使用JSON。但是如果浏览器没有实现它,它就会退回到自己的解析器。

Stringify-object是yeoman团队制作的一个很好的NPM库:https://www.npmjs.com/package/stringify-object

npm install stringify-object

然后:

const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);

显然,只有当循环对象使用JSON.stringify()会失败时,它才有趣;