Converting an object to a string
如何将javascript对象转换为字符串?
例子:
1 2 3 | var o = {a:1, b:2} console.log(o) console.log('Item: ' + o) |
输出:
Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
我建议使用
1 2 3 4 5 | var obj = { name: 'myObj' }; JSON.stringify(obj); |
使用javascript string()函数。
1 | String(yourobject); //returns [object Object] |
或
1 | JSON.stringify(yourobject) |
.
当然,要将对象转换为字符串,您必须使用自己的方法,例如:
1 2 3 4 5 6 7 8 9 10 | function objToString (obj) { var str = ''; for (var p in obj) { if (obj.hasOwnProperty(p)) { str += p + '::' + obj[p] + ' '; } } return str; } |
实际上,上面只是显示了一般的方法;您可能希望使用类似http://phpjs.org/functions/var_export:578或http://phpjs.org/functions/var_dump:604的方法。
或者,如果您不使用方法(作为对象属性的函数),您可能可以使用新的标准(但不能在旧的浏览器中实现,尽管您也可以找到一个实用工具来帮助它们实现),json.stringify()。但同样,如果对象使用的函数或其他属性不可序列化为JSON,这将不起作用。
使用
例子:
1 2 3 4 | var o = {a:1, b:2}; console.log(o); console.log('Item: ' + o); console.log('Item: ', o); // :) |
输出:
1 2 3 | Object { a=1, b=2} // useful Item: [object Object] // not useful Item: Object {a: 1, b: 2} // Best of both worlds! :) |
参考:https://developer.mozilla.org/en-us/docs/web/api/console.log
编辑不要使用此答案,因为它在Internet Explorer中不起作用。使用Gary Chambers溶液。
tosource()是您正在寻找的函数,它将以json的形式写出。
1 2 3 4 | var object = {}; object.first ="test"; object.second ="test2"; alert(object.toSource()); |
一种选择:
另一个选项(正如soktinpk在评论中指出的那样),更好地用于控制台调试IMO:
这里的所有解决方案对我都不起作用。很多人都这么说json.stringify,但它会切断函数,对于我在测试它时尝试过的一些对象和数组来说,它看起来相当糟糕。
我自己做了一个解决方案,至少在Chrome中有效。把它贴在这里,这样任何在谷歌上查到的人都能找到它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | //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("") } |
编辑:我知道这个代码是可以改进的,但从来没有做过。用户Andrey在这里提出了改进意见:
Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.
你自己承担风险,因为我根本没有核实过。请随时提出任何其他改进建议作为评论。
如果您只是输出到控制台,那么可以使用
如果您知道对象只是一个布尔值、日期、字符串、数字等…函数的作用很好。我最近发现,这对于处理jquery的$.每个函数的值很有用。
例如,下面将把"value"中的所有项转换为字符串:
1 2 3 | $.each(this, function (name, value) { alert(String(value)); }); |
详细信息如下:
http://www.w3schools.com/jsref/jsref_string.asp
1 2 3 4 5 6 7 8 | 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); |
我在找这个,写了一个很深的递归缩进:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 ' \t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1); }).join(',') + ' ' + indent + '}]'[+isArray]; default: return obj.toString(); } } |
用法:
如果只想看到要调试的对象,可以使用
1 2 | var o = {a:1, b:2} console.dir(o) |
JSON方法远不如gecko engine.tosource()原语。
有关比较测试,请参阅SO文章响应。
另外,上面的答案是http://forums.devshed.com/javascript-development-115/to source-with-arrays-in-ie-386109.html,与json(另一篇文章http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json通过"extjs json encode source code"使用)一样,它无法处理循环引用,并且不完整。下面的代码显示了它的(spoof的)限制(修正为处理数组和没有内容的对象)。
(直接链接到//forums.devshed.com/中的代码…/tosource-with-array-in-ie-386109)中的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 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([ ' testing:',objRA[i][0],objRA[i][1], ' .toSource()',(obj=eval(objRA[i][1])).toSource(), ' toSource() spoof:',obj.spoof() ].join(' ')); |
显示:
1 2 3 4 5 6 7 8 9 10 11 12 | 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")] |
和
1 2 3 4 5 6 7 8 9 | 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")] |
和
1 2 3 4 5 6 7 8 9 10 11 | 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] |
1。
1 | JSON.stringify(o); |
Item: {"a":"1","b":"2"}
2。
1 2 3 4 | 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); |
Item: {a:1, b:2}
如果只关心字符串、对象和数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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; } |
因为火狐不把某些对象串成屏幕对象;如果你想得到相同的结果,比如:
1 | npm install stringify-object |
然后:
1 2 | const stringifyObject = require('stringify-object'); stringifyObject(myCircularObject); |
显然,只有当你有一个圆形物体,它会在
看看jquery json插件
在其核心,它使用json.stringify,但如果浏览器不实现它,它会返回到自己的解析器。
事实上,现有答案中缺少一个简单的选项(对于最近的浏览器和node.js):
1 | console.log('Item: %o', o); |
我更愿意这样做,因为
1 2 3 4 5 6 7 8 | var o = {a:1, b:2}; o.toString=function(){ return 'a='+this.a+', b='+this.b; }; console.log(o); console.log('Item: ' + o); |
因为javascript v1.0在任何地方都可以工作(甚至是IE)这是一种本机方法,允许在调试和生产过程中对对象进行非常昂贵的查看。https://developer.mozilla.org/en/docs/web/javascript/reference/global_objects/object/toString
使用实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var Ship=function(n,x,y){ this.name = n; this.x = x; this.y = y; }; Ship.prototype.toString=function(){ return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y; }; alert([new Ship('Star Destroyer', 50.001, 53.201), new Ship('Millennium Falcon', 123.987, 287.543), new Ship('TIE fighter', 83.060, 102.523)].join(' '));//now they can battle! //"Star Destroyer" located at: x:50.001 y:53.201 //"Millennium Falcon" located at: x:123.987 y:287.543 //"TIE fighter" located at: x:83.06 y:102.523 |
另外,作为奖励
10如果您使用的是Dojo JavaScript框架,那么已经有了一个内置函数:dojo.tojson(),可以这样使用。
1 2 3 4 | var obj = { name: 'myObj' }; dojo.toJson(obj); |
它将返回一个字符串。如果要将对象转换为JSON数据,请添加第二个参数true。
1 | dojo.toJson(obj, true); |
http://dojotoolkit.org/reference-guide/dojo/tojson.html dojo-tojson
以你为例,我认为
使用方法1会在控制台中使用一个很好的下拉列表,因此一个长的对象会很好地工作。
对于非嵌套对象:
1 2 3 | Object.entries(o).map(x=>x.join(":")).join(" ") |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | /* 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 +=" "; 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(", ") +" "; res += ident +"]"; } else { var new_ident = ident + inc_ident; res +="{"; res += (show_types == true) ?"/* typeobj:" + typeof(obj) +"*/" :""; res +=" "; var arr = []; for(var key in obj) { arr.push(new_ident + '"' + key +"" :" + getAsText(obj[key], inc_ident, show_types, new_ident)); } res += arr.join(", ") +" "; res += ident +"} "; } return res; }; |
使用实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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(); |
您的_Object1.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "str" :"hello" , "arr" : [ "1" , "2" , "3" , 4 ], "b" : true, "vobj" : { "str" :"hello2" } } |
您的_Object2.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { /* typeobj: object*/ "str" :"hello" /* typeobj: string*/, "arr" : [ /* typeobj: object*/ "1" /* typeobj: string*/, "2" /* typeobj: string*/, "3" /* typeobj: string*/, 4/* typeobj: number*/ ], "b" : true/* typeobj: boolean*/, "vobj" : { /* typeobj: object*/ "str" :"hello2" /* typeobj: string*/ } } |
似乎json接受了第二个参数,可以帮助函数-replacer,这以最优雅的方式解决了转换的问题:
1 2 3 4 5 6 | JSON.stringify(object, (key, val) => { if (typeof val === 'function') { return String(val); } return val; }); |
如果你可以使用木屑,你可以这样做:
1 2 3 | > var o = {a:1, b:2}; > '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}' '{a:1, b:2}' |
使用lodash
1 2 | > _.map(o, (value, key) => key + ':' + value) [ 'a:1', 'b:2' ] |
和
如果您可以使用ES6模板字符串,这也适用于:
1 2 | > `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}` '{a:1, b:2}' |
请注意,这不会在对象中递归:
1 2 3 | > var o = {a:1, b:{c:2}} > _.map(o, (value, key) => `${key}:${value}`) [ 'a:1', 'b:[object Object]' ] |
就像node的
1 2 | > util.inspect(o) '{ a: 1, b: { c: 2 } }' |
如果您希望在内联表达式类型的情况下将变量转换为字符串的最小方法,那么
如果"variablename"是一个对象,而您使用的是空字符串连接操作,那么它将给出恼人的
我希望这个例子能帮助所有正在处理对象数组的人。
1 2 3 4 5 6 7 8 | var data_array = [{ "id":"0", "store":"ABC" },{ "id":"1", "store":"XYZ" }]; console.log(String(data_array[1]["id"]+data_array[1]["store"])); |
我需要制作一个更可配置的EDOCX1版本(14),因为我必须添加注释并了解json路径:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | 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 '[ '; case 'OPEN_OBJ': return '{ '; case 'VAL': return `${t1}// ${path} ${t1}${v(key)}: ${v(prop)}, `; case 'ARR_VAL': return `${t1}// ${path} ${t1}${v(prop)}, `; case 'OBJ_KEY': return `${t1}// ${path} ${t1}${v(key)}: `; case 'CLOSE_ARR': case 'CLOSE_OBJ': return `${t}${type === 'CLOSE_ARR' ? ']' : '}'}${depth ? ',' : ';'} `; default: throw new Error('Unknown type:', type); } }).join(''); const s = objToStr(someObj); console.log(s); |
如果您只想得到一个字符串输出,那么这应该是有效的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function objToString (obj) { var str = '{'; if(typeof obj=='object') { for (var p in obj) { if (obj.hasOwnProperty(p)) { str += p + ':' + objToString (obj[p]) + ','; } } } else { if(typeof obj=='string') { return '"'+obj+'"'; } else { return obj+''; } } return str.substring(0,str.length-1)+"}"; } |
如果不将join()应用于对象。
1 2 3 4 5 | const obj = {one:1, two:2, three:3}; let arr = []; for(let p in obj) arr.push(obj[p]); const str = arr.join(','); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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(',')+'}'; } |