【问题标题】:How to export json file by ruby?如何通过 ruby​​ 导出 json 文件?
【发布时间】:2016-03-21 04:31:42
【问题描述】:

我想通过 ruby​​ 导出像 sample.json 这样的 JSON 文件。 (我会将 json.file 上传到 S3)

我期待下面的方式,但是它需要事先准备好 json 文件。有没有办法在ruby上导出json文件?

File.open("sample.json", "w") do |f|
   f.write(sample_data.to_json)
end

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"
}

【问题讨论】:

标签: ruby json


【解决方案1】:

这是一个简单的例子(这几乎就是你正在做的):

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

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

【讨论】:

    【解决方案2】:

    AFAIU,有一项任务是读取包含 json 的文件并将其写回(可能经过一些修改。)

    首先,上面的代码不是合法的json,右方括号前的逗号应该去掉。

    去掉逗号后内容存入文件sample.json:

    ▶ require 'json'
    #⇒ true
    ▶ json = JSON.parse File.read '/tmp/a.json'
    #⇒ {
    #         "asset_ids" => [
    #    [0] "this is id"
    #  ],
    #      "contract_url" => "http://hoge.com/",
    #       "description" => "",
    #  "description_mime" => "text/x-markdown; charset=UTF-8",
    #      "divisibility" => 1,
    #            "issuer" => "Fuga",
    #   "link_to_website" => false,
    #              "name" => "HogeHoge",
    #        "name_short" => "Hoge",
    #              "type" => "Currency",
    #           "version" => "1.0"
    # }
    

    好的,我们刚刚将内容放入 ruby​​ 哈希中。将其存储回来:

    ▶ File.write 'sample.json', JSON.dump(json)
    #⇒ 260
    

    以人类可读的漂亮格式存储它:

    ▶ File.write 'sample.json', JSON.pretty_generate(json)
    #⇒ 260
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-21
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      相关资源
      最近更新 更多