在Ruby on Rails中将字符串散列到json

时间:2015-06-24 10:29:36

标签: ruby-on-rails

string = "{:from_zip_code=>\"90066\", :to_zip_code=>\"12345\", [{:amount=>\"2.8\", :add_on_type=>\"US-A-RR\", :requires_all_of=>{:requires_one_of=>{:add_on_type_v7=>[\"US-A-COD\"]}}, {:amount=>\"12.2\", :add_on_type=>\"US-A-REG\", :prohibited_with_any_of=>{:add_on_type_v7=>[\"SC-A-HP\"]}}, {:amount=>\"5.15\", :add_on_type=>\"US-A-RD\", :requires_all_of=>{:requires_one_of=>{:add_on_type_v7=>[\"US-A-COD\"]}}, :prohibited_with_any_of=>{:add_on_type_v7=>[\"SC-A-HP\"]}}, {:add_on_type=>\"SC-A-INS\", :prohibited_with_any_of=>{:add_on_type_v7=>[\"US-A-REG\", \"US-A-INS\"]}, :missing_data=>\"InsuredValue\"}, {:add_on_type=>\"US-A-NND\"}]}}"

请你帮我把这个字符串改成json或hash,如下所示

{ :from_zip_code => "90066",
  :to_zip_code => "12345",
  [
    {
      :amount => "2.8",
      ...
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

 gem install json

您需要在代码中使用gem:

 require 'rubygems'
 require 'json'

然后你可以像这样解析你的JSON字符串:

JSON.parse(string)