function objToString (obj) {
var tabjson=[];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
tabjson.push('"'+p +'"'+ ':' + obj[p]);
}
} tabjson.push()
return '{'+tabjson.join(',')+'}';
}
//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("")
}
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'));
显示:
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")]
/*
This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
Params:
obj - your object
inc_ident - can be " " or "\t".
show_types - show types of object or not
ident - need for recoursion but you can not set this parameter.
*/
function getAsText(obj, inc_ident, show_types, ident) {
var res = "";
if (!ident)
ident = "";
if (typeof(obj) == "string") {
res += "\"" + obj + "\" ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
res += obj;
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (obj instanceof Array) {
res += "[ ";
res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var new_ident = ident + inc_ident;
var arr = [];
for(var key in obj) {
arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "]";
} else {
var new_ident = ident + inc_ident;
res += "{ ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var arr = [];
for(var key in obj) {
arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "}\r\n";
}
return res;
};
使用示例:
var obj = {
str : "hello",
arr : ["1", "2", "3", 4],
b : true,
vobj : {
str : "hello2"
}
}
var ForReading = 1, ForWriting = 2;
var fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
f1.Write(getAsText(obj, "\t"));
f1.Close();
f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
f2.Write(getAsText(obj, "\t", true));
f2.Close();
如果'variablename'是一个对象并且您使用空字符串连接操作,它将给出令人讨厌的 [object Object] ,在这种情况下,您可能希望Gary C.对发布的问题进行极大的回复 JSON.stringify 答案,您可以在Mozilla的开发者网络上阅读该问题在that answer at the top的链接 .
3
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(',')+'}';
}
29 回答
使用javascript String()函数 .
要么
.
因为firefox没有将某些对象字符串化为屏幕对象;如果你想得到相同的结果,例如:
JSON.stringify(obj)
:Take a look at the jQuery-JSON plugin
从本质上讲,它使用JSON.stringify,但如果浏览器没有实现,则会回退到自己的解析器 .
我建议使用JSON.stringify,它将对象中的变量集转换为JSON字符串 . 大多数现代浏览器本机支持此方法,但对于那些不支持的方法,您可以包含JS version:
当然,要将对象转换为字符串,您必须使用自己的方法,例如:
实际上,上面只是展示了一般方法;你可能希望使用像http://phpjs.org/functions/var_export:578或http://phpjs.org/functions/var_dump:604这样的东西
或者,如果您不使用方法(作为对象属性的函数),您可以使用新标准(但在旧版浏览器中未实现,但您也可以找到一个实用程序来帮助它们),JSON .stringify() . 但是,如果对象使用不可序列化为JSON的函数或其他属性,则无法工作 .
使用
console
保持简单,您只需使用逗号而不是+
.+
将尝试将对象转换为字符串,而逗号将在控制台中单独显示它 .例:
输出:
参考:https://developer.mozilla.org/en-US/docs/Web/API/Console.log
EDIT 不要使用此答案,因为它在Internet Explorer中不起作用 . 使用Gary Chambers解决方案 .
toSource()是您正在寻找的函数,它将其写为JSON .
One option :
console.log('Item: ' + JSON.stringify(o));
Another option (正如 soktinpk 在评论中指出的那样),以及更好的控制台调试IMO:
console.log('Item: ', o);
这里没有一个解决方案适合我 . JSON.stringify似乎是很多人所说的,但它削减了函数,对于我在测试它时尝试的一些对象和数组看起来很糟糕 .
我制作了自己的解决方案,至少在Chrome中有效 . 在此处发布,以便在Google上查找此内容的任何人都可以找到它 .
编辑:我知道这个代码可以改进,但从来没有做过 . 用户andrey建议改进here评论:
使用它需要您自担风险,因为我根本没有验证它 . 作为评论,请随意建议任何其他改进 .
如果您只是输出到控制台,则可以使用
console.log('string:', obj)
. 请注意 comma .如果你知道对象只是一个布尔,日期,字符串,数字等... javascript String()函数工作得很好 . 我最近发现这对于处理来自jquery的$ .each函数的值很有用 .
例如,以下内容会将“value”中的所有项目转换为字符串:
更多细节在这里:
http://www.w3schools.com/jsref/jsref_string.asp
我正在寻找这个,并写了一个深度递归的缩进:
用法:
objToString({ a: 1, b: { c: "test" } })
如果您只是想查看调试对象,可以使用
1 .
2 .
JSON方法非常不如Gecko引擎.toSource()原语 .
有关比较测试,请参阅SO article response .
此外,answer above引用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通过"ExtJs JSON encode source code"使用)无法处理循环引用并且不完整 . 下面的代码显示了它的限制(更正为处理没有内容的数组和对象) .
(direct link to code in //forums.devshed.com/ ... /tosource-with-arrays-in-ie-386109)
显示:
和
和
如果您只关心字符串,对象和数组:
stringify-object
是自由团队制作的一个很好的npm图书馆:https://www.npmjs.com/package/stringify-object然后:
显然只有当你的圆形对象失败时才会有意思
JSON.stringify();
由于Javascript v1.0适用于所有地方(甚至是IE),因此这是一种原生方法,允许在调试和 生产环境 时对象的非常昂贵的外观https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
有用的例子
另外,作为奖金
如果您正在使用Dojo javascript框架,那么已经有一个构建函数来执行此操作:dojo.toJson()将使用它 .
这将返回一个字符串 . 如果要将对象转换为json数据,请添加第二个参数true .
http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson
使用示例:
your_object1.txt:
your_object2.txt:
对于你的例子,我认为
console.log("Item:",o)
会最容易的 . 但是,console.log("Item:" + o.toString)
也会奏效 .使用第一个方法在控制台中使用一个很好的下拉列表,因此一个长对象可以很好地工作 .
对于非嵌套对象:
我希望这个例子能够帮助所有那些正在研究对象数组的人
如果你可以使用lodash你可以这样做:
使用lodash
map()
,您也可以迭代对象 . 这会将每个键/值条目映射到其字符串表示形式:并且
join()
将数组条目放在一起 .如果您可以使用ES6模板字符串,这也有效:
请注意,这不会通过Object递归:
像node's util.inspect()会做:
如果你不会将join()播放到Object .
如果你想要一个简单的方法将一个变量转换为一个内联表达式类型的字符串,
''+variablename
是我打过的最好的 .如果'variablename'是一个对象并且您使用空字符串连接操作,它将给出令人讨厌的
[object Object]
,在这种情况下,您可能希望Gary C.对发布的问题进行极大的回复JSON.stringify
答案,您可以在Mozilla的开发者网络上阅读该问题在that answer at the top的链接 .