2016-04-21 45 views
3
我有問題

散列到操縱一個鍵值對字符串的ruby.The字符串散列:轉換一個字符串,它是一個鍵值對,紅寶石

"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" 

記住這是一個string.Now我想作一個哈希象下面這樣:

"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" 

我已經搜索了很多,使用方法的splitruby string class.Like波紋管:

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

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

這給了我一個錯誤的hash.like波紋管:

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

specialties是一個數組,它應該有所有的值,但它只有返回的第一個值。

我無法理解如何將此字符串轉換爲正確的散列。 請幫幫我吧。

非常感謝。

回答

3

您可以用花括號{}裏面的字符串,然後使用JSON

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

你讓我很快樂的人感謝這麼much.I是多麼愚蠢這樣的小動作和工作的偉大解析它。 再次感謝男人。 – monsur

+1

np。樂於幫助 :) – Santhosh