【问题标题】:Convert a string which is a key value pair to hash in ruby将作为键值对的字符串转换为 ruby​​ 中的哈希
【发布时间】:2016-08-14 12:07:24
【问题描述】:

我在操作字符串的键值对以在 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"

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

# 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 是一个数组,它应该包含所有值,但它只返回第一个值。

我不明白如何将此字符串转换为正确的哈希值。 请帮帮我。

非常感谢。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 你让我的一天非常感谢。我太笨了这么个小把戏,而且效果很好。再次感谢伙计。
    • np。乐于助人:)
    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    相关资源
    最近更新 更多