[Ruby]データ構造をJSONに変換する
結論から言うと、JSON.pretty_generateを使うと簡単にできます。
#!/usr/bin/env ruby
require 'json'
data = {
:net => {
:hostname => "dqneo.example.com"
},
:iptables => [
{:port => '1122', :proto => 'tcp', :source => '10.0.10.2/32'},
{:port => '161', :proto => 'udp'}
],
:users => [
{ :name => 'dqneo', :password => 'himitsu' },
],
:tz => "Asia/Tokyo",
:mongodb => {:dbpath =>"/data/db"},
}
puts JSON.pretty_generate(data);
実行結果
{
"net": {
"hostname": "dqneo.example.com"
},
"iptables": [
{
"port": "1122",
"proto": "tcp",
"source": "10.0.10.2/32"
},
{
"port": "161",
"proto": "udp"
}
],
"users": [
{
"name": "dqneo",
"password": "himitsu"
}
],
"tz": "Asia/Tokyo",
"mongodb": {
"dbpath": "/data/db"
}
}
\(できた)/
カテゴリ:
Ruby