use*_*174 926 javascript string object tostring
如何将JavaScript对象转换为字符串?
例:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Run Code Online (Sandbox Code Playgroud)
输出:
对象{a = 1,b = 2} //非常好的可读输出:)
项目:[object Object] //不知道里面是什么:(
Gar*_*ers 1296
我建议使用JSON.stringify,它将对象中的变量集转换为JSON字符串.大多数现代浏览器本机支持此方法,但对于那些不支持此方法的浏览器,您可以包含JS版本:
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
Run Code Online (Sandbox Code Playgroud)
Vik*_*ote 103
使用javascript String()函数.
String(yourobject); //returns [object Object]
Run Code Online (Sandbox Code Playgroud)
要么
JSON.stringify(yourobject)
Run Code Online (Sandbox Code Playgroud)
.
Bre*_*mir 85
当然,要将对象转换为字符串,您必须使用自己的方法,例如:
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
Run Code Online (Sandbox Code Playgroud)
实际上,上面只是说明了一般方法; 你可能希望使用http://phpjs.org/functions/var_export:578或http://phpjs.org/functions/var_dump:604之类的东西
或者,如果您没有使用方法(作为对象属性的函数),您可以使用新标准(但在旧版浏览器中未实现,但您也可以找到一个实用程序来帮助它们),JSON .stringify().但是,如果对象使用不可序列化为JSON的函数或其他属性,那么这将不起作用.
Luk*_*uke 75
保持简单console,你可以使用逗号代替+.该+会尝试将对象转换为字符串,而逗号将在控制台中单独显示它.
例:
var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o); // :)
Run Code Online (Sandbox Code Playgroud)
输出:
Object { a=1, b=2} // useful
Item: [object Object] // not useful
Item: Object {a: 1, b: 2} // Best of both worlds! :)
Run Code Online (Sandbox Code Playgroud)
参考:https://developer.mozilla.org/en-US/docs/Web/API/Console.log
Gaz*_*ler 33
编辑 不要使用此答案,因为它在Internet Explorer中不起作用.使用Gary Chambers解决方案.
toSource()是您正在寻找的函数,它将其写为JSON.
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
Run Code Online (Sandbox Code Playgroud)
nab*_*abn 31
一种选择:
console.log('Item: ' + JSON.stringify(o));

另一种选择(正如soktinpk在评论中指出的那样),以及更好的控制台调试IMO:
console.log('Item: ', o);

Hou*_*ter 20
这里没有一个解决方案适合我.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("")
}
Run Code Online (Sandbox Code Playgroud)
编辑:我知道这个代码可以改进,但从来没有做过.用户安德烈提出的改善这里与评论:
这是一个稍微改变的代码,它可以处理'null'和'undefined',也不会添加过多的逗号.
使用它需要您自担风险,因为我根本没有验证过.作为评论,请随意建议任何其他改进.
Jak*_*rew 16
如果你知道对象只是一个布尔,日期,字符串,数字等... javascript String()函数工作得很好.我最近发现这对于处理来自jquery的$ .each函数的值很有用.
例如,以下内容会将"value"中的所有项目转换为字符串:
$.each(this, function (name, value) {
alert(String(value));
});
Run Code Online (Sandbox Code Playgroud)
更多细节在这里:
http://www.w3schools.com/jsref/jsref_string.asp
小智 13
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);
Run Code Online (Sandbox Code Playgroud)
Syl*_*nPV 11
我正在寻找这个,并写了一个深度递归的缩进:
function objToString(obj, ndeep) {
if(obj == null){ return String(obj); }
switch(typeof obj){
case "string": return '"'+obj+'"';
case "function": return obj.name || obj.toString();
case "object":
var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
return '{['[+isArray] + Object.keys(obj).map(function(key){
return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
}).join(',') + '\n' + indent + '}]'[+isArray];
default: return obj.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
用法: objToString({ a: 1, b: { c: "test" } })
JSON方法非常不如Gecko引擎.toSource()原语.
有关比较测试,请参阅SO文章响应.
另外,上面的答案是指http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html,与JSON一样,(另一篇文章http:// www.davidpirek.com/blog/object-to-string-how-to-deserialize-json使用via "ExtJs JSON编码源代码")无法处理循环引用并且不完整.下面的代码显示了它(欺骗)的限制(更正为处理没有内容的数组和对象).
(直接链接到//forums.devshed.com/ .../tosource-with-arrays-in-ie-386109中的代码)
javascript:
Object.prototype.spoof=function(){
if (this instanceof String){
return '(new String("'+this.replace(/"/g, '\\"')+'"))';
}
var str=(this instanceof Array)
? '['
: (this instanceof Object)
? '{'
: '(';
for (var i in this){
if (this[i] != Object.prototype.spoof) {
if (this instanceof Array == false) {
str+=(i.match(/\W/))
? '"'+i.replace('"', '\\"')+'":'
: i+':';
}
if (typeof this[i] == 'string'){
str+='"'+this[i].replace('"', '\\"');
}
else if (this[i] instanceof Date){
str+='new Date("'+this[i].toGMTString()+'")';
}
else if (this[i] instanceof Array || this[i] instanceof Object){
str+=this[i].spoof();
}
else {
str+=this[i];
}
str+=', ';
}
};
str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+(
(this instanceof Array)
? ']'
: (this instanceof Object)
? '}'
: ')'
);
return str;
};
for(i in objRA=[
[ 'Simple Raw Object source code:',
'[new Array, new Object, new Boolean, new Number, ' +
'new String, new RegExp, new Function, new Date]' ] ,
[ 'Literal Instances source code:',
'[ [], {}, true, 1, "", /./, function(){}, new Date() ]' ] ,
[ 'some predefined entities:',
'[JSON, Math, null, Infinity, NaN, ' +
'void(0), Function, Array, Object, undefined]' ]
])
alert([
'\n\n\ntesting:',objRA[i][0],objRA[i][1],
'\n.toSource()',(obj=eval(objRA[i][1])).toSource(),
'\ntoSource() spoof:',obj.spoof()
].join('\n'));
Run Code Online (Sandbox Code Playgroud)
显示:
testing:
Simple Raw Object source code:
[new Array, new Object, new Boolean, new Number, new String,
new RegExp, new Function, new Date]
.toSource()
[[], {}, (new Boolean(false)), (new Number(0)), (new String("")),
/(?:)/, (function anonymous() {}), (new Date(1303248037722))]
toSource() spoof:
[[], {}, {}, {}, (new String("")),
{}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]
Run Code Online (Sandbox Code Playgroud)
和
testing:
Literal Instances source code:
[ [], {}, true, 1, "", /./, function(){}, new Date() ]
.toSource()
[[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))]
toSource() spoof:
[[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")]
Run Code Online (Sandbox Code Playgroud)
和
testing:
some predefined entities:
[JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined]
.toSource()
[JSON, Math, null, Infinity, NaN, (void 0),
function Function() {[native code]}, function Array() {[native code]},
function Object() {[native code]}, (void 0)]
toSource() spoof:
[{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined]
Run Code Online (Sandbox Code Playgroud)
小智 7
1.
JSON.stringify(o);
Run Code Online (Sandbox Code Playgroud)
货号:{"a":"1","b":"2"}
2.
var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);
Run Code Online (Sandbox Code Playgroud)
货号:{a:1,b:2}
实际上,现有答案中缺少一个简单的选项(对于最新的浏览器和Node.js):
console.log('Item: %o', o);
Run Code Online (Sandbox Code Playgroud)
我希望这样做JSON.stringify()有一定的局限性(例如,采用圆形结构)。
stringify-object是 yeoman 团队制作的一个很好的 npm 库:https : //www.npmjs.com/package/stringify-object
npm install stringify-object
Run Code Online (Sandbox Code Playgroud)
然后:
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
Run Code Online (Sandbox Code Playgroud)
显然只有当你有一个会失败的圆形对象时才有趣 JSON.stringify();
对于非嵌套对象:
Object.entries(o).map(x=>x.join(":")).join("\r\n")
Run Code Online (Sandbox Code Playgroud)
由于 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(',')+'}';
}
Run Code Online (Sandbox Code Playgroud)
如果你只关心字符串、对象和数组:
function objectToString (obj) {
var str = '';
var i=0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(typeof obj[key] == 'object')
{
if(obj[key] instanceof Array)
{
str+= key + ' : [ ';
for(var j=0;j<obj[key].length;j++)
{
if(typeof obj[key][j]=='object') {
str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
}
else
{
str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
}
}
str+= ']' + (i > 0 ? ',' : '')
}
else
{
str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
}
}
else {
str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
}
i++;
}
}
return str;
}
Run Code Online (Sandbox Code Playgroud)
似乎JSON接受了第二个可能对函数有用的参数-replacer,这以最优雅的方式解决了转换问题:
JSON.stringify(object, (key, val) => {
if (typeof val === 'function') {
return String(val);
}
return val;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1501576 次 |
| 最近记录: |