在Ruby中,如何从哈希输出json并为其赋予换行符和制表符 [英] In Ruby, how to output json from hash and give it line breaks and tabs

查看:167
本文介绍了在Ruby中,如何从哈希输出json并为其赋予换行符和制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化{"key" => "value"}以将其转换为:

I'm trying to format {"key" => "value"} to turn it into :

{
    "key" : "value"
}

用于写入json文件. 现在我正在做:

for writing into a json file. right now im doing :

hash = {"key" => "value"}
puts hash.to_json.gsub('{', '{\n\t')

开始.然后输出

{\n\t"key":"value"}

为什么我不能换行?

推荐答案

是的,很漂亮的东西,是的,避免了正则表达式!

Yay for pretty things and yay for avoiding regexen!

使用内置的 JSON.pretty_generate 方法

require 'json'
puts JSON.pretty_generate hash, options

是的!

以下是选项:

  • indent:用于缩进级别的字符串(默认值:''),
  • space:放在:,分隔符(默认值:'')之后的字符串,
  • space_before:放在:对定界符(默认值:'')之前的字符串,
  • object_nl:放置在JSON对象末尾的字符串(默认值:'')
  • array_nl:放在JSON数组末尾的字符串(默认值:''),
  • allow_nan:true如果应生成NaNInfinity-Infinity,否则如果遇到这些值,则将引发异常.此选项默认为false.
  • max_nesting:要从中生成JSON的数据结构中允许的最大嵌套深度.使用:max_nesting => false禁用深度检查,默认为100.
  • indent: a string used to indent levels (default: ''),
  • space: a string that is put after, a : or , delimiter (default: ''),
  • space_before: a string that is put before a : pair delimiter (default: ''),
  • object_nl: a string that is put at the end of a JSON object (default: ''),
  • array_nl: a string that is put at the end of a JSON array (default: ''),
  • allow_nan: true if NaN, Infinity, and -Infinity should be generated, otherwise an exception is thrown if these values are encountered. This options defaults to false.
  • max_nesting: The maximum depth of nesting allowed in the data structures from which JSON is to be generated. Disable depth checking with :max_nesting => false, it defaults to 100.

这篇关于在Ruby中,如何从哈希输出json并为其赋予换行符和制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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