将作为键值对的字符串转换为ruby中的哈希值

时间:2016-04-21 10:38:39

标签: ruby string ruby-on-rails-4 hash

我在操作ruby中的键值键值对时遇到问题。字符串是:

"specialties":["Corporate Housing","Temporary Housing","Furnished Apartment","Short Term Rentals"],"website":"http://www.demo.com","universalName":"some-corporate-housing","size":"51-200 employees","description":"demo description","industry":"Hospitality","companyType":"Privately Held","companyName":"some Corporate Housing","includeSecondAd":true,"yearFounded":1995,"headquarters":{"city":"Austin","zip":"78759","state":"Texas","street1":"9606 N. Mopac Expressway","country":"United States","street2":"Suite 500"},"homeUrl":"https://www.some.com/company/some-corporate-housing"

记住它是一个字符串。现在我想制作如下的哈希:

"specialties":["Corporate Housing","Temporary Housing","Furnished Apartment","Short Term Rentals"],

"website":"http://www.demo.com",

"universalName":"some-corporate-housing",

"size":"51-200 employees",

"description":"demo description",

"industry":"Hospitality",

"companyType":"Privately Held",

"companyName":"some Corporate Housing",

"includeSecondAd":true,

"yearFounded":1995,

"headquarters":

  {"city":"Austin",
   "zip":"78759",
   "state":"Texas",
   "street1":"9606 N. Mopac Expressway",
   "country":"United States",
   "street2":"Suite 500"
  },

"homeUrl":"https://www.some.com/company/cws-corporate-housing"

我搜索了很多并使用了split类的ruby string方法。如下所示:

# test reffers to the string .
hash = {}
test.split(',').each do |pair|

        key,value = pair.split(/:/) 
        hash[key.to_sym] = value
end

这给了我一个错误的哈希。如下:

hash["specialties"] #=> "Corporate Housing",

因为specialties是一个数组,它应该包含所有值,但它只返回第一个值。

我无法理解如何将此字符串转换为正确的哈希值。 请帮帮我们。

非常感谢。

1 个答案:

答案 0 :(得分:3)

您可以将字符串括在花括号{}中,然后使用json解析它

require 'json'
json_str = "{#{ str }}"
hash = JSON.parse(json_str)