Javascript 对象到格式化字符串 [英] Javascript object to formatted string

查看:68
本文介绍了Javascript 对象到格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象输出为带有格式的可读字符串(结构类似于

)?

没有 jQuery 可能.

我的对象使用 console.log 看起来像这样.

对象书名:《又一刺》类型:树"选项:对象分页:20"结构类型:1"列:对象...描述:这是一个字符串"...

将其转换为结构化字符串的最佳方法是什么?

我的尝试:

我尝试使用 stringify() 来获取 JSON 结构.然后我可以编写自己的解析器,但也许已经有任何实现?

解决方案

JSON.stringify 包含一个格式化参数:

<块引用>

JSON.stringify(value[, replacer [, space]])

空格参数可用于控制最终字符串中的间距.如果它是一个数字,则字符串化中的连续级别将每个缩进这么多空格字符(最多 10 个).如果它是一个字符串,则后续级别将以此字符串(或它的前十个字符)缩进.

使用制表符模仿标准的漂亮印刷外观

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

这足以满足您的需要吗?例如.试试:

 JSON.stringify( object, null, 2 );

否则,http://code.google.com/p/google-code-prettify/ 是一个独立的 JSON 到 HTML 漂亮的打印机.我相信被 stackoverflow 和谷歌代码使用.

How to output an object as a readable string with formatting (structured like with <pre>) ?

No jQuery possible.

My object looks like this using console.log.

Object
   title: "Another sting"
   type: "tree"
   options: Object
      paging: "20"
      structuretype: "1"
   columns: Object
      ...
   description: "This is a string"
   ...

What is the best to convert it to a structured string?

My attempt:

I tried using stringify() to get the JSON structure. I could then write my own parser, but maybe there are already any implementations?

解决方案

JSON.stringify includes a formatting argument:

JSON.stringify(value[, replacer [, space]])

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

Using a tab character mimics standard pretty-print appearance

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

Is that enough formatting for what you need? E.g. try:

 JSON.stringify( object, null, 2 );

Otherwise, http://code.google.com/p/google-code-prettify/ is a standalone JSON to HTML pretty printer. Used by stackoverflow and google code, I believe.

这篇关于Javascript 对象到格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆