2

I'd like to export JSON file like sample.json by ruby. (I'll upload the json.file to S3)

I expect the following way, however it needs to prepare json file before. Are there any way to export json file on ruby?

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"
}
Toshi
  • 1,293
  • 3
  • 19
  • 37

2 Answers2

7

Here's a simple example (which is pretty much what you are doing):

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

I am using JSON.pretty_generate instead of to_json to format JSON output, else it would print everything in one line.

shivam
  • 16,048
  • 3
  • 56
  • 71
1

AFAIU, there is a task to both read the file containing json and to write it back (possible after some modifications.)

First of all, the code above is not valid json, the comma right before closing square bracket should be removed.

After the comma is removed and content is stored in the file 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"
# }

OK, we just got the content into ruby hash. To store it back:

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

To store it in human readable pretty format:

▶ File.write 'sample.json', JSON.pretty_generate(json)
#⇒ 260
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160