i trying extract json objects include hotel in line1 of address, keep getting following error:
line1_hotel.rb:5:in `block in <main>': undefined method `[]' nil:nilclass (nomethoderror) line1_hotel.rb:4:in `each' line1_hotel.rb:4:in `group_by' line1_hotel.rb:4:in `<main>' my ruby version 2.1.4p265, , code below. have used square bracket notation access data in nested keys before. in case seems failing. i've looked @ group_by ruby doc there no detail @ whether accepts kind of notation. also, if don't nest works in other examples.
require 'json' array = json.parse file.read('gaps4.json') result = array.group_by |e| e['address']['line1'] =~ /hotel/ ? true : false end file.open('testtrue.json', 'w') |file| file << json.pretty_generate(result[true]) end file.open('testfalse.json', 'w') |file| file << json.pretty_generate(result[false]) end an example "snippet" json data trying extract. example 1 object has hotel in line1 whereas other doesn't. (there many records):
[ { "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" } } } ]
e['address']['line1'] should e['location']['address']['line1']. re-check json structure.
the reason error e['address'] nil , e['address']['line1'] try call ['line'], in fact #[] method, on nil.
plus, whether not producing json yourself, fine protect code accidental errors:
e['location'] && # make sure location given e['location']['address'] && # make sure address given e['location']['address']['line1'] =~ /hotel/ ? true : false just not fail if no location presented.
Comments
Post a Comment