如何以正确的格式写入 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5507512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write to a JSON file in the correct format
提问by dt1000
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 格式将其写入文件?
回答by Mike Lewis
回答by Anders 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"
}
回答by Haseeb Eqx
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
在 ruby >= 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 }
回答by daggett
To make this work on Ubuntu Linux:
要在 Ubuntu Linux 上执行此操作:
I installed the Ubuntu package ruby-json:
apt-get install ruby-jsonI wrote the script in
${HOME}/rubybin/jsonDEMO$HOME/.bashrcincluded:${HOME}/rubybin:${PATH}
我安装了 Ubuntu 软件包 ruby-json:
apt-get install ruby-json我把脚本写在
${HOME}/rubybin/jsonDEMO$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

