我在操作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
是一个数组,它应该包含所有值,但它只返回第一个值。
我无法理解如何将此字符串转换为正确的哈希值。 请帮帮我们。
非常感谢。
答案 0 :(得分:3)
您可以将字符串括在花括号{}
中,然后使用json解析它
require 'json'
json_str = "{#{ str }}"
hash = JSON.parse(json_str)