Ruby解析JSON.load和YAML.load生成不同的密钥类型

时间:2015-05-26 11:04:28

标签: ruby json yaml

我一直在寻找序列化/反序列化数据的不同选项。

我注意到的一件事是,在将json字符串转换为哈希时,它使用字符串文字作为键。 当我将yaml字符串转换为哈希时,它使用符号作为键。我认为这是因为对于json,它们的键值必须是字符串吗?

当它转换回哈希值时,是否有可用于指定或控制此行为的标志?

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}"

产生以下输出:

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 个答案:

答案 0 :(得分:2)

根据http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html

您可以使用JSON.parse,它有一个选项symbolize_names

JSON.parse(File.read('data.json'), symbolize_names: true)