将作为键值对的字符串转换为 ruby​​ 中的散列

mon*_*sur 3 ruby string hash ruby-on-rails-4

我在操纵字符串的键值对以在 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"
Run Code Online (Sandbox Code Playgroud)

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

"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"
Run Code Online (Sandbox Code Playgroud)

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

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

        key,value = pair.split(/:/) 
        hash[key.to_sym] = value
end
Run Code Online (Sandbox Code Playgroud)

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

hash["specialties"] #=> "Corporate Housing",
Run Code Online (Sandbox Code Playgroud)

作为specialties一个数组,它应该具有所有值,但它只返回第一个值。

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

非常感谢。

San*_*osh 5

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

require 'json'
json_str = "{#{ str }}"
hash = JSON.parse(json_str)
Run Code Online (Sandbox Code Playgroud)