简体   繁体   English

如何以正确的格式写入JSON文件

[英]How to write to a JSON file in the correct format

I am creating a hash in Ruby and want to write it to a JSON file, in the correct format. 我正在Ruby中创建哈希,并希望以正确的格式将其写入JSON文件。

Here is my code: 这是我的代码:

tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
fJson = File.open("public/temp.json","w")
fJson.write(tempHash)
fJson.close

And here is the contents of the resulting file: 这是结果文件的内容:

key_aval_akey_bval_b

I'm using Sinatra (don't know what version) and Ruby v 1.8.7. 我正在使用Sinatra(不知道哪个版本)和Ruby v 1.8.7。

How can I write this to the file in the correct JSON format? 如何以正确的JSON格式将其写入文件?

Require the JSON library, and use to_json . 需要JSON库,并使用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: 您的temp.json文件现在看起来像:

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

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

This question is for ruby 1.8 but it still comes on top when googling. 这个问题是针对ruby 1.8的,但是在谷歌搜索时它仍然是最重要的。

in ruby >= 1.9 you can use 在红宝石> = 1.9中可以使用

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 除了在其他答案中提到的以外,在ruby 1.8中,您还可以使用一种衬里形式

File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

To make this work on Ubuntu Linux: 要在Ubuntu Linux上执行此操作:

  1. I installed the Ubuntu package ruby-json: 我安装了Ubuntu软件包ruby-json:

     apt-get install ruby-json 
  2. I wrote the script in ${HOME}/rubybin/jsonDEMO 我在${HOME}/rubybin/jsonDEMO编写了脚本

  3. $HOME/.bashrc included: $HOME/.bashrc包括:

     ${HOME}/rubybin:${PATH} 

(On this occasion I also typed the above on the bash command line.) (在这种情况下,我还在bash命令行上输入了以上内容。)

Then it worked when I entered on the command line: 然后,当我在命令行上输入时它就起作用了:

jsonDemo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM