Ruby:无法使用group_by方法

时间:2015-07-17 15:40:28

标签: ruby regex json

我正在尝试提取包含地址的第1行中的Hotel的JSON对象,但我不断收到以下错误:

line1_hotel.rb:5:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
    from line1_hotel.rb:4:in `each'
    from line1_hotel.rb:4:in `group_by'
    from line1_hotel.rb:4:in `<main>'

我的Ruby版本是2.1.4p265,我的代码如下。我之前使用方括号表示法来访问嵌套键中的数据。但在这种情况下似乎失败了。我已经查看了group_by Ruby doc,但是它是否接受这种表示法没有任何细节。此外,如果我没有嵌套,则可以在其他示例中使用。

require 'json'

array = JSON.parse File.read('gaps4.json')
result = array.group_by do |e|
  e['address']['line1'] =~ /Hotel/ ? true : false
end

File.open('testtrue.json', 'w') do |file|
  file << JSON.pretty_generate(result[true])
end

File.open('testfalse.json', 'w') do |file|
  file << JSON.pretty_generate(result[false])
end

一个示例&#34;代码段&#34;从我试图提取的JSON数据。例如,一个对象在第1行中具有Hotel,而在另一个对象中没有。 (有很多记录):

[
     {
        "id": "242595",
        "name": "San Lorenzo - Wimbledon",
        "phone": "+442089468463",
        "email": "live@sanlorenzo.com",
        "website": "https://sanlorenzosw19.squarespace.com/new-page/",
        "location": {
          "latitude": 51.4221176,
          "longitude": -0.208713,
          "address": {
            "line1": "38 Wimbledon Hill Road",
            "line2": "",
            "line3": "",
            "postcode": "SW19 7PA",
            "city": "London",
            "country": "UK"
          }
        }
      },
      {
        "id": "101055",
        "name": "Sanderson",
        "phone": "+442073005588",
        "email": "restaurant.resuk@mhgc.com",
        "website": "",
        "location": {
          "latitude": 51.51747,
          "longitude": -0.13724,
          "address": {
            "line1": "Sanderson Hotel",
            "line2": "50 Berners Street",
            "line3": "",
            "postcode": "W1T 3NG",
            "city": "London",
            "country": "UK"
          }
        }
      }
    ]

1 个答案:

答案 0 :(得分:2)

e['address']['line1']应为e['location']['address']['line1']。只需重新检查json结构。

您收到错误的原因是e['address']nile['address']['line1']尝试调用['line'],实际上是#[]方法,在nil

另外,无论您是否自己生成此json,都可以保护代码免受意外错误的影响:

e['location'] &&              # make sure location given
e['location']['address'] &&   # make sure address given
e['location']['address']['line1'] =~ /Hotel/ ? true : false

如果没有出现位置,请不要失败。