2

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}
1
  • It seems that you've duplicated question stackoverflow.com/questions/7543779/…. There is no options, I presume, and if your hash doesn't contain mixed key types the best way is deep convert hash keys to symbols Commented May 26, 2015 at 11:16

1 Answer 1

2

According to http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html

You can use JSON.parse instead, which has an option symbolize_names.

JSON.parse(File.read('data.json'), symbolize_names: true)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.