I've been looking at different options for serializing/de-serializing data.
One thing I noticed, that when converting a json string to a hash it uses string literals as keys. When I convert a yaml string to a hash, it uses symbols for keys. I assume this is because for json, they key values must be strings?
Are there any flags that can be used to specify or control this behaviour when it converts back to a hash?
require 'json'
require 'yaml'
test_hash = {:name => "TestHash",
:key1 => "value1",
:key2 => 500
}
# Convert the Hash to JSON/YAML strings
#
yaml_string = test_hash.to_yaml
json_string = test_hash.to_json
puts "Hash to YAML #{yaml_string}"
puts "Hash to JSON #{json_string}"
# Now use the JSON/YAML methods to convert back
# to a hash
#
hash_from_yaml = YAML.load(yaml_string)
hash_from_json = JSON.load(json_string)
puts "Original Hash #{test_hash}"
puts "YAML Hash #{hash_from_yaml}"
puts "JSON Hash #{hash_from_json}"
The produces the following output:
Hash to YAML ---
:name: TestHash
:key1: value1
:key2: 500
Hash to JSON {"name":"TestHash","key1":"value1","key2":500}
Original Hash {:name=>"TestHash", :key1=>"value1", :key2=>500}
YAML Hash {:name=>"TestHash", :key1=>"value1", :key2=>500}
JSON Hash {"name"=>"TestHash", "key1"=>"value1", "key2"=>500}