How to write to a JSON file in the correct format

后端 未结 4 395
长发绾君心
长发绾君心 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"}
    
    0 讨论(0)
  • 2020-12-02 07:01

    This question is for ruby 1.8 but it still comes on top when googling.

    in ruby >= 1.9 you can use

    File.write("public/temp.json",tempHash.to_json)
    

    other than what mentioned in other answers, in ruby 1.8 you can also use one liner form

    File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
    
    0 讨论(0)
  • 2020-12-02 07:03

    With formatting

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

    Output

    {
        "key_a":"val_a",
        "key_b":"val_b"
    }
    
    0 讨论(0)
  • 2020-12-02 07:05

    To make this work on Ubuntu Linux:

    1. I installed the Ubuntu package ruby-json:

      apt-get install ruby-json
      
    2. I wrote the script in ${HOME}/rubybin/jsonDEMO

    3. $HOME/.bashrc included:

      ${HOME}/rubybin:${PATH}
      

    (On this occasion I also typed the above on the bash command line.)

    Then it worked when I entered on the command line:

    jsonDemo
    
    0 讨论(0)
提交回复
热议问题