JSON - Syntax Data is represented in name/value pairs. Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma). Square brackets hold arrays and values are separated by ,(comma).
First, to write data to a JSON file, we must create a JSON string of the data with JSON. stringify . This returns a JSON string representation of a JavaScript object, which can be written to a file.
A JSON Object is an entity in JSON which is enclosed in curly brackets. It is written in the unordered set of name and value pairs in which the name should be followed by “:” (colon), and the name/value pairs need to be separated using “,” (comma). It can be used when key names are arbitrary strings.
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"}
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.
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 }
To make this work on Ubuntu Linux:
I installed the Ubuntu package ruby-json:
apt-get install ruby-json
I wrote the script in ${HOME}/rubybin/jsonDEMO
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With