I have text file that looks like this:
[{"id":1,"title":"book1","author":"person1","pages":"10"}, {"id":2,"title":"book2","author":"person2","age":"20"},{"id":3,"title":"book3","author":"person3","age":"30"}, {"id":4,"title":"book4","author":"person4","age":"40"}]
I wish to parse this in Ruby to obtain an array of hashes arr
from which I could obtain, for example, values of the author field:
person1
person2
person3
person4
How can I do that?
CodePudding user response:
You can write
require 'json'
arr = JSON.parse '[{"id":1,"title":"book1","author":"person1","pages":"10"}, {"id":2,"title":"book2","author":"person2","age":"20"},{"id":3,"title":"book3","author":"person3","age":"30"}, {"id":4,"title":"book4","author":"person4","age":"40"}]'
#=> [
# {"id"=>1, "title"=>"book1", "author"=>"person1", "pages"=>"10"},
# {"id"=>2, "title"=>"book2", "author"=>"person2", "age"=>"20"},
# {"id"=>3, "title"=>"book3", "author"=>"person3", "age"=>"30"},
# {"id"=>4, "title"=>"book4", "author"=>"person4", "age"=>"40"}
# ]
Then
puts arr.map { |h| h[:author] }
#=> ["person1", "person2", "person3", "person4"]
CodePudding user response:
It's very unsophisticated, but if your text file truly is formatted so neatly as Ruby code, then you can just eval
it:
irb(main):001:0> data = eval('[{"id":1,"title":"book1","author":"person1","pages":"10"}, {"id":2,"title":"book2","author":"person2","age":"20"},{"id":3,"title":"book3","author":"person3","age":"30"}, {"id":4,"title":"book4","author":"person4","age":"40"}]')
=> [{:id=>1, :title=>"book1", :author=>"person1", :pages=>"10"}, {:id=>2, :title=>"book2", :author=>"person2", :age=>"20"}, {:id=>3, :title=>"book3", :author=>"person3", :age=>"30"}, {:id=>4, :title=>"book4", :author=>"person4", :age=>"40"}]
irb(main):002:0> data.collect { |x| x[:author] }
=> ["person1", "person2", "person3", "person4"]