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

后端 未结 3 1303
庸人自扰
庸人自扰 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: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. :)

提交回复
热议问题