如何将JSON转换为Ruby哈希


137

我有一个持有以下值的JSON对象:

@value = {"val":"test","val1":"test1","val2":"test2"}

我想在Ruby中循环遍历以获得键/值对。当我使用时@each,它不会遍历该对象,因为它不是Ruby哈希形式:

@value = {"val"=>"test","val1"=>"test1","val2"=>"test2"}

如何将上述JSON对象转换为Ruby哈希?

Answers:


250

接下来的代码片段呢?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}

7
value = '{"val":"test","val1":"test1","val2":"test2"}'可能更具可读性。
luckykrrish 2012年

40

您还可以使用Rails的with_indifferent_access方法,以便可以使用符号或字符串访问主体。

value = '{"val":"test","val1":"test1","val2":"test2"}'
json = JSON.parse(value).with_indifferent_access

然后

json[:val] #=> "test"

json["val"] #=> "test"

有人知道大型散列对象的资源消耗是否更大?我是Ruby / Rails的新手,但是假设这重复键值对吗?
乔纳森

4

假设您的某个地方散布着JSON散列,要将其自动转换为类似WarHog的版本,请将JSON散列内容包装在%q{hsh}标记中。

就像WarHog的答案一样,这似乎会自动添加所有必需的转义文本。



1

令我惊讶的是,没有人指出JSON的[]方法,它使从JSON解码和编码变得非常容易和透明。

如果object是类字符串,则解析该字符串,并将解析后的结果作为Ruby数据结构返回。否则,从Ruby数据结构对象生成JSON文本并返回它。

考虑一下:

require 'json'

hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"

str 现在包含JSON编码 hash

使用以下命令可以很容易地将其撤消:

JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}

需要to_s为该类定义自定义对象,并在其内部将对象转换为Hash,然后to_json在其上使用。


0

您可以使用nice_hash gem:https : //github.com/MarioRuiz/nice_hash

require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'

# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json

# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)

# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.