How to write to a JSON file in the correct format

后端 未结 4 404
长发绾君心
长发绾君心 2020-12-02 06:05

I am creating a hash in Ruby and want to write it to a JSON file, in the correct format.

Here is my code:

tempHash = {
    \"key_a\" => \"val_a\         


        
4条回答
  •  心在旅途
    2020-12-02 06:52

    Require the JSON library, and use to_json.

    require 'json'
    tempHash = {
        "key_a" => "val_a",
        "key_b" => "val_b"
    }
    File.open("public/temp.json","w") do |f|
      f.write(tempHash.to_json)
    end
    

    Your temp.json file now looks like:

    {"key_a":"val_a","key_b":"val_b"}
    

提交回复
热议问题