Parsing from a JSON file in Ruby and Extract numbers from Nested Hashes

You can use Array#map to collect the reviews.

reviews = json['sentiment_analysis'][0]
positive_reviews = reviews['positive']
negative_reviews = reviews['negative']

positive_reviews.map { |review| review['score'] }
=> [0.6748984055823062, 0.6280145725181376]

negative_reviews.map { |review| review['score'] }
=> [-0.7923352042939829, -0.5734506634410159]

Hope this helps!


Using the JSON class:

Importing a file:

require "json"
file = File.open "/path/to/your/file.json"
data = JSON.load file

Optionally, you can close it now:

file.close

The file looks like this:

{
  "title": "Facebook",
  "url": "https://www.facebook.com",
  "posts": [
    "lemon-car",
    "dead-memes"
  ]
}

The file is now able to be read like this:

data["title"]
=> "Facebook"
data.keys
=> ["title", "url", "posts"]
data['posts']
=> ["lemon-car", "dead-memes"]
data["url"]
=> "https://www.facebook.com"

Hope this helped!


Parse Data from File:

data_hash = JSON.parse(File.read('file-name-to-be-read.json'))

Then just map over the data!

reviews = data_hash['sentiment_analysis'].first
reviews.map do |sentiment, reviews|
  puts "#{sentiment} #{reviews.map { |review| review['score'] }}"
end

I think this is the simplest answer.

Tags:

Ruby

Parsing

Json