如何通过ruby导出json文件?

lal*_*ala 1 ruby json

我想通过ruby导出诸如sample.json之类的JSON文件。(我将json.file上传到S3)

我期望以下方式,但是它需要先准备json文件。有什么办法可以在ruby上导出json文件吗?

File.open("sample.json", "w") do |f|
   f.write(sample_data.to_json)
end
Run Code Online (Sandbox Code Playgroud)

sample.json

{
  "asset_ids": [
    "this is id",
  ],
  "contract_url": "http://hoge.com/",
  "name_short": "Hoge",
  "name": "HogeHoge",
  "issuer": "Fuga",
  "description": "",
  "description_mime": "text/x-markdown; charset=UTF-8",
  "type": "Currency",
  "divisibility": 1,
  "link_to_website": false,
  "version": "1.0"
}
Run Code Online (Sandbox Code Playgroud)

shi*_*vam 5

这是一个简单的示例(这几乎就是您正在做的事情):

hash = {:h => 1, :k => 2, :v => 3}
File.open("sample.json", "wb") { |file| file.puts JSON.pretty_generate(hash) }
Run Code Online (Sandbox Code Playgroud)

我使用JSON.pretty_generate而不是to_json格式化JSON输出,否则它将在一行中打印所有内容。