51

Now I am working on extracting information from a JSON file in Ruby. Then how can I extract just the numbers next to the word 'score' from the following text file? For example, I want to get 0.6748984055823062, 0.6280145725181376 on and on.

{
  "sentiment_analysis": [
    {
      "positive": [
        {
          "sentiment": "Popular",
          "topic": "games",
          "score": 0.6748984055823062,
          "original_text": "Popular games",
          "original_length": 13,
          "normalized_text": "Popular games",
          "normalized_length": 13,
          "offset": 0
        },
        {
          "sentiment": "engaging",
          "topic": "pop culture-inspired games",
          "score": 0.6280145725181376,
          "original_text": "engaging pop culture-inspired games",
          "original_length": 35,
          "normalized_text": "engaging pop culture-inspired games",
          "normalized_length": 35,
          "offset": 370
        },
     "negative": [
    {
      "sentiment": "get sucked into",
      "topic": "the idea of planning",
      "score": -0.7923352042939829,
      "original_text": "Students get sucked into the idea of planning",
      "original_length": 45,
      "normalized_text": "Students get sucked into the idea of planning",
      "normalized_length": 45,
      "offset": 342
    },
    {
      "sentiment": "be daunted",
      "topic": null,
      "score": -0.5734506634410159,
      "original_text": "initially be daunted",
      "original_length": 20,
      "normalized_text": "initially be daunted",
      "normalized_length": 20,
      "offset": 2104
    },

What I have tried is that I could read a file and set the text file to a hash variable using the JSON method.

require 'json'
json = JSON.parse(json_string)
1

3 Answers 3

82

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!

Sign up to request clarification or add additional context in comments.

3 Comments

You should not use File.read, which loads the whole file in memory. File.open works fine with JSON.load.
If this is the option you choose, don't forget to file.close!
You need JSON.load instead of JSON.parse, parse only takes a string, load will take a file. You also need require "json" instead of include.
29

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.

3 Comments

yeah but then you can don't know how to read it apart from just trying it out in IRB
@MichalŠtein - this answer seems quite simple, and handles closing the file (your answer doesn't) - please explain your concern with this answer?
The answer does not say what to do after you load it. And I am gonna add the file closing, that's a great idea.
9

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!

4 Comments

It greatly worked as you suggested. Thank you! Could you explain what the [0] means in json['sentiment_analysis'][0]['positive']?
json['sentiment_analysis'] holds an array of objects and the data you're looking for is present in the first index. So, you use [0] to index into the object and then parse the "positives" object. Does this make sense?
Ok I see. Then could you take a look at the text file above again? I added "negatives" more to the text. In this case, should I use json['sentiment_analysis'][0]['negative'] or json['sentiment_analysis'][1]['negative']?
@SookieJ Updated the answer. Have a look and let me know if it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.