将对象转换为字符串
如何将 JavaScript 对象转换为字符串?
示例:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
Object { a=1, b=2} // 非常好的可读输出:)
Item: [object Object] // 不知道里面有什么:(
How can I convert a JavaScript object into a string?
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 :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
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 通过 "ExtJs JSON 编码源代码") 无法处理循环引用并且不完整。下面的代码显示了它的(欺骗)限制(已更正以处理没有内容的数组和对象)。
(直接链接到论坛中的代码。 in-ie-386109)
显示:
和
devshed.com/ ... /tosource-with-arrays -
JSON methods are quite inferior to the Gecko engine .toSource() primitive.
See the SO article response for comparison tests.
Also, the answer above refers to http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html which, like JSON, (which the other article http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json uses via "ExtJs JSON encode source code") cannot handle circular references and is incomplete. The code below shows it's (spoof's) limitations (corrected to handle arrays and objects without content).
(direct link to code in //forums.devshed.com/ ... /tosource-with-arrays-in-ie-386109)
which displays:
and
and
stringify-object
是 yeoman 团队制作的一个很好的 npm 库:https: //www.npmjs.com/package/stringify-object然后:
显然,只有当你有一个会因
JSON.stringify();
失败的循环对象时,它才有意义stringify-object
is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-objectthen:
Obviously it's interesting only if you have circular object that would fail with
JSON.stringify();
由于 Firefox 不会将某些对象字符串化为屏幕对象;如果您想获得相同的结果,例如:
JSON.stringify(obj)
:As firefox does not stringify some object as screen object ; if you want to have the same result such as :
JSON.stringify(obj)
:如果您只关心字符串、对象和数组:
If you only care about strings, objects, and arrays:
查看 jQuery-JSON 插件
核心,它使用 JSON.stringify 但如果浏览器没有实现它,则回退到它自己的解析器。
Take a look at the jQuery-JSON plugin
At its core, it uses JSON.stringify but falls back to its own parser if the browser doesn't implement it.
如果您可以使用 lodash,您可以这样做:
使用 lodash
map()
您也可以迭代对象。这会将每个键/值条目映射到其字符串表示形式:
并且
join()
将数组条目放在一起。如果您可以使用 ES6 模板字符串,这也适用:
请注意,这不会通过对象递归:
就像 node 的
util.inspect()
将执行以下操作:If you can use lodash you can do it this way:
With lodash
map()
you can iterate over Objects as well.This maps every key/value entry to its string representation:
And
join()
put the array entries together.If you can use ES6 Template String, this works also:
Please note this do not goes recursive through the Object:
Like node's
util.inspect()
will do:由于 Javascript v1.0 可以在任何地方使用(甚至是 IE)
这是一种本机方法,允许在调试和生产过程中使对象具有非常定制的外观
https://developer.mozilla.org/en/docs /Web/JavaScript/Reference/Global_Objects/Object/toString
有用的示例
另外,作为奖励
Since Javascript v1.0 works everywhere (even IE)
this is a native approach and allows for a very costomised look of your object while debugging and in production
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
Usefull example
Also, as a bonus
循环引用
通过使用下面的 replacer< /strong> 我们可以生成更少冗余的 JSON - 如果源对象包含对某个对象的多重引用,或者包含循环引用 - 那么我们通过特殊的路径字符串引用它(类似于 JSONPath) - 我们按如下方式使用它
:'$.'}${pp}` : value; !init ? (init=value) : (val===init ? val="#REF:$" : 0); if(!pp && isComplex) v.set(value, path); return val; } } // --------------- // TEST // --------------- // gen obj with duplicate references let a = { a1: 1, a2: 2 }; let b = { b1: 3, b2: "4" }; let obj = { o1: { o2: a }, b, a }; // duplicate reference a.a3 = [1,2,b]; // circular reference b.b3 = a; // circular reference let s = JSON.stringify(obj, refReplacer(), 4); console.log(s);奖励:这是此类序列化的反函数
Circular References
By using below replacer we can produce less redundant JSON - if source object contains multi-references to some object, or contains circular references - then we reference it by special path-string (similar to JSONPath) - we use it as follows
:'$.'}${pp}` : value; !init ? (init=value) : (val===init ? val="#REF:$" : 0); if(!pp && isComplex) v.set(value, path); return val; } } // --------------- // TEST // --------------- // gen obj with duplicate references let a = { a1: 1, a2: 2 }; let b = { b1: 3, b2: "4" }; let obj = { o1: { o2: a }, b, a }; // duplicate reference a.a3 = [1,2,b]; // circular reference b.b3 = a; // circular reference let s = JSON.stringify(obj, refReplacer(), 4); console.log(s);BONUS: and here is inverse function of such serialisation
使用示例:
your_object1.txt:
your_object2.txt:
example to use:
your_object1.txt:
your_object2.txt:
对于你的例子,我认为
console.log("项目:",o)
会是最简单的。但,
console.log("Item:" + o.toString)
也会起作用。
使用方法一会在控制台中使用一个很好的下拉菜单,因此长对象可以很好地工作。
For your example, I think
console.log("Item:",o)
would be easiest. But,
console.log("Item:" + o.toString)
would also work.
Using method number one uses a nice dropdown in the console, so a long object would work nicely.
我希望这个例子对所有处理对象数组的人有所帮助
I hope this example will help for all those who all are working on array of objects
如果您不使用 join() 到 Object.
If you wont aplay join() to Object.
我建议使用
JSON.stringify< /code>
,它将对象中的变量集转换为 JSON 字符串。
大多数现代浏览器本身支持此方法,但对于那些不支持此方法的浏览器,您可以添加 JS 版本。
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.
使用 javascript String() 函数
或stringify()
Use javascript String() function
or stringify()
为了让
console
保持简单,您可以只使用逗号而不是+
。+
将尝试将对象转换为字符串,而逗号将在控制台中单独显示它。示例:
输出:
参考:https://developer.mozilla.org/en-US/文档/Web/API/Console.log
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.Example:
Output:
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log
当然,要将对象转换为字符串,你要么必须使用自己的方法,例如:
实际上,上面只是展示了一般方法;您可能希望使用类似 http://phpjs.org/functions/var_export:578 或http://phpjs.org/functions/var_dump:604
或者,如果您不使用方法(作为对象的属性),您也许可以使用新标准(但在旧版浏览器中未实现,尽管您也可以找到一个实用程序来帮助它们),JSON.stringify()。但同样,如果对象使用不可序列化为 JSON 的函数或其他属性,则该方法将不起作用。
更新:
更现代的解决方案是:
或者:
Sure, to convert an object into a string, you either have to use your own method, such as:
Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://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.
Update:
A more modern solution would be:
or:
编辑 不要使用此答案,因为它仅适用于某些版本的 Firefox。没有其他浏览器支持它。使用Gary Chambers解决方案。
toSource() 是您正在寻找的函数,它将把它写成 JSON。
EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.
toSource() is the function you are looking for which will write it out as JSON.
一个选项:
console.log('Item: ' + JSON.stringify(o));
另一个选项(正如评论中指出的soktinpk),并且更适合控制台调试IMO:
console.log('Item: ', o);
One option:
console.log('Item: ' + JSON.stringify(o));
Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:
console.log('Item: ', o);
这里的解决方案都不适合我。 JSON.stringify 似乎是很多人所说的,但它删除了函数,并且对于我在测试它时尝试的某些对象和数组来说似乎相当糟糕。
我制作了自己的解决方案,至少可以在 Chrome 中使用。将其发布在这里,以便任何在 Google 上查找此内容的人都可以找到它。
编辑:我知道这段代码可以改进,但只是从来没有抽出时间去做。用户 andrey 在此处建议进行改进,并发表评论:
使用它需要您自担风险,因为我根本没有验证过它。请随时以评论的形式提出任何其他改进建议。
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.
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.
EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:
Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.
如果您只是输出到控制台,则可以使用console.log('string:', obj)。注意逗号。
If you're just outputting to the console, you can use
console.log('string:', obj)
. Notice the comma.如果您知道该对象只是布尔值、日期、字符串、数字等,则 javascript String() 函数可以正常工作。我最近发现这在处理来自 jquery 的 $.each 函数的值时很有用。
例如,以下内容会将“value”中的所有项目转换为字符串:
此处有更多详细信息:
http://www.w3schools。 com/jsref/jsref_string.asp
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.
For example the following would convert all items in "value" to a string:
More details here:
http://www.w3schools.com/jsref/jsref_string.asp
我一直在寻找这个,并写了一个带有缩进的深度递归:
用法:
objToString({ a: 1, b: { c: "test" } })
I was looking for this, and wrote a deep recursive one with indentation :
Usage :
objToString({ a: 1, b: { c: "test" } })
实际上,现有答案中缺少一个简单的选项(对于最近的浏览器和 Node.js):
我更喜欢这个,因为
JSON.stringify()
有一定的限制(例如,具有循环结构)。There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:
I would prefer this as
JSON.stringify()
has certain limitations (e.g. with circular structures).如果您只想查看对象以进行调试,您可以使用
If you just want to see the object for debugging, you can use
1.
2.
1.
2.
看来 JSON 接受第二个可以帮助函数的参数 - replacer,这解决了以最优雅的方式转换的问题:
It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:
对于非嵌套对象:
For non-nested objects: