Javascript 将对象转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5612787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:03:34  来源:igfitidea点击:

Converting an object to a string

javascriptstringobjectserializationtostring

提问by user680174

How can I convert a JavaScript object into a string?

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

Example:

例子:

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

Output:

输出:

Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(

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

回答by Gary Chambers

I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string. Most modern browsers support this method natively, but for those that don't, you can include a JS version:

我建议使用JSON.stringify,它将对象中的变量集转换为 JSON 字符串。大多数现代浏览器本机支持此方法,但对于那些不支持的浏览器,您可以包含一个JS 版本

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);

回答by Vikram Pote

Use javascript String()function

使用 javascript String()函数

 String(yourobject); //returns [object Object]

or stringify()

字符串化()

JSON.stringify(yourobject)

回答by Brett Zamir

Sure, to convert an object into a string, you either have to use your own method, such as:

当然,要将对象转换为字符串,您必须使用自己的方法,例如:

function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}

Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578or http://phpjs.org/functions/var_dump:604

其实,上面只是展示了一般的做法;您可能希望使用类似http://phpjs.org/functions/var_export:578http://phpjs.org/functions/var_dump:604 的东西

or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.

或者,如果您不使用方法(作为对象属性的函数),您可以使用新标准(但未在旧浏览器中实现,但您也可以找到一个实用程序来帮助它们),JSON .stringify()。但同样,如果对象使用不可序列化为 JSON 的函数或其他属性,那将不起作用。

回答by Luke

Keeping it simple with console, you can just use a comma instead of a +. The +will try to convert the object into a string, whereas the comma will display it separately in the console.

保持简单console,您可以只使用逗号而不是+。该+会尝试将对象转换为字符串,而逗号将在控制台中单独显示它。

Example:

例子:

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

Output:

输出:

Object { a=1, b=2}           // useful
Item: [object Object]        // not useful
Item:  Object {a: 1, b: 2}   // Best of both worlds! :)

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log

参考:https: //developer.mozilla.org/en-US/docs/Web/API/Console.log

回答by Gazler

EDITDo not use this answer as it does not work in Internet Explorer. Use Gary Chamberssolution.

编辑不要使用此答案,因为它在 Internet Explorer 中不起作用。使用加里钱伯斯解决方案。

toSource()is the function you are looking for which will write it out as JSON.

toSource()是您正在寻找的函数,它将把它写成 JSON。

var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());

回答by nabn

One option:

一种选择

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

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

o is printed as a string

o 打印为字符串

Another option(as soktinpkpointed out in the comments), and better for console debugging IMO:

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

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

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

o is printed as an object, which you could drill down if you had more fields

o 被打印为一个对象,如果你有更多的字段,你可以向下钻取

回答by Houshalter

None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.

这里没有一个解决方案对我有用。JSON.stringify 似乎是很多人所说的,但它删除了函数,并且对于我在测试时尝试过的某些对象和数组来说似乎很糟糕。

I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.

我制作了自己的解决方案,至少可以在 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("")
}

EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement herewith the comment:

编辑:我知道这段代码可以改进,但只是从来没有时间去做。用户 andrey在这里提出了改进意见:

Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.

这里有一点点改动的代码,可以处理'null'和'undefined',也不要添加过多的逗号。

Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.

使用它需要您自担风险,因为我根本没有验证它。随意提出任何其他改进作为评论。

回答by Alexandre R. Janini

If you're just outputting to the console, you can use console.log('string:', obj). Notice the comma.

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

回答by Jake Drew

In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.

在您知道对象只是布尔值、日期、字符串、数字等的情况下……javascript String() 函数工作得很好。我最近发现这在处理来自 jquery 的 $.each 函数的值时很有用。

For example the following would convert all items in "value" to a string:

例如,以下将“value”中的所有项目转换为字符串:

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

More details here:

更多细节在这里:

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

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

回答by sunny rai

var obj={
name:'xyz',
Address:'123, Somestreet'
 }
var convertedString=JSON.stringify(obj) 
 console.log("literal object is",obj ,typeof obj);
 console.log("converted string :",convertedString);
 console.log(" convertedString type:",typeof convertedString);