In Ruby, how to output json from hash and give it line breaks and tabs

后端 未结 3 1300
庸人自扰
庸人自扰 2020-12-14 23:55

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

{
    \"key\" : \"value\"
}

for writing into a json file. ri

相关标签:
3条回答
  • 2020-12-15 00:13

    Yay for pretty things and yay for avoiding regexen!

    Use the built-in JSON.pretty_generate method

    require 'json'
    puts JSON.pretty_generate hash, options
    

    Yay!

    Here's the options:

    • 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.
    0 讨论(0)
  • 2020-12-15 00:16

    As @naomik mentions, try using the builtin JSON.pretty_generate with a tab for the "indent" option, for example:

    require 'json'
    h = {:key => :value}
    puts JSON.pretty_generate(h, :indent => "\t")
    # {
    #         "key": "value"
    # }
    

    The values for the "opts" argument to pretty_generate are documented at generate.

    0 讨论(0)
  • 2020-12-15 00:18

    For both line breaks and tabs, try

    require 'json'
    hash = {foo: 'bar'}
    JSON.pretty_generate(hash, {indent: "\t", object_nl: "\n"})
    

    NB! If you use single quotes with newlines ("\n") or tabs ("\t") they will not be interpreted as newlines but as an ordinary string containing one backslash and a letter. This is a common mistake. :)

    0 讨论(0)
提交回复
热议问题