将对象转换为字符串

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

例: java

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

输出: jquery

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


#1楼

看一下jQuery-JSON插件 数组

从本质上讲,它使用JSON.stringify,但若是浏览器没有实现,则会回退到本身的解析器。 浏览器


#2楼

若是你知道对象只是一个布尔,日期,字符串,数字等... javascript String()函数工做得很好。 我最近发现这对于处理来自jquery的$ .each函数的值颇有用。 app

例如,如下内容会将“value”中的全部项目转换为字符串: 函数

$.each(this, function (name, value) {
  alert(String(value));
});

更多细节在这里: 测试

http://www.w3schools.com/jsref/jsref_string.asp ui


#3楼

由于firefox没有将某些对象字符串化为屏幕对象; 若是你想获得相同的结果,例如: 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(',')+'}';
}

#4楼

这里没有一个解决方案适合我。 JSON.stringify彷佛是不少人所说的,但它削减了函数,对于我在测试时尝试的一些对象和数组看起来很糟糕。

我制做了本身的解决方案,至少在Chrome中有效。 在此处发布,以便在Google上查找此内容的任何人均可以找到它。

//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("")
}

编辑:我知道这个代码能够改进,但历来没有作过。 用户安德烈提出的改善这里与评论:

这是一个稍微改变的代码,它能够处理'null'和'undefined',也不会添加过多的逗号。

使用它须要您自担风险,由于我根本没有验证过。 做为评论,请随意建议任何其余改进。


#5楼

若是您只是输出到控制台,则可使用console.log('string:', obj) 。 注意逗号

相关文章
相关标签/搜索