带有符号和字符串的JSON不可读

时间:2016-01-11 07:42:42

标签: ruby json

我有以下JSON:

{ :a => 1, "b" => "test" }

jsonObject[:b]没有给我任何数据,而对于所有键都是字符串的JSON,

{ "a" => 1, "b" => "test" }

它工作正常:

jsonObject[:b] # => "test"

是否存在在同一JSON对象中使用符号和键的约束?

2 个答案:

答案 0 :(得分:0)

我建议在使用之前将JSON解析为哈希,比如

require 'json'
JSON.parse("{...}")

并通过

将哈希转换为JSON字符串
hash.to_json

符号和字符串的所有键都被转换为字符串。

require 'json'
a = {:a => '12', 'b' => '23'}
p aa = a.to_json #=> "{\"a\":\"12\",\"b\":\"23\"}"
p JSON.parse(aa) #=> {"a"=>"12", "b"=>"23"}

答案 1 :(得分:0)

您有时可能会处理简单的Hash,有时会处理HashWithIndifferentAccess。例如,Rails'params允许默认情况下无关紧要的访问。这可能解释了你的困惑:

hash = { :a => 1, 'b' => 2 }

hash[:a]
#=> 1
hash['b']
#=> 2
hash[:b]
#=> nil

但是HashWithIndifferentAccess

hash = hash.with_indifferent_access

hash[:a]
#=> 1
hash['b']
#=> 2
hash[:b]
#=> 2