0

I'm interning at a company and was given the following instructions:

"You'll find student records in a text file (students.json) - one student per line. Write a program to calculate the average grades of the class."

The student file in question was a gist with .txt extension and this is an example of the content:

{"first name": "mary", "last name": "roberts", "grade": 78}
{"first name": "jason", "last name": "mchale", "grade": 82}
{"first name": "ciaron", "last name": "smith", "grade": 63}
{"first name": "sarah", "last name": "johnson", "grade": 91}

This is my first time working with JSON so I figured I needed to covert it to a hash or something so I can work with the data more easily.

I tried to do so using the following method:

require 'json'

def distance
  file = File.open("students.txt", "r")

  students = ""

  file.each do |line|
    students << line
  end
  file.close

  puts JSON.parse(students)
end

But I got the error:

JSON::ParserError: 757: unexpected token at '{"first name": "mary", "last name": "roberts", "grade": 78}
{"first name": "jason", "last name": "mchale", "grade": 82}...

I had a look at this question and it suggests that I don't actually have JSON but a hash written as a String. Unfortunately running

hash.eval(students)

only gives me the first student record and not the rest. I'm a little confused about what I'm actually working with, is it a plain text file, a hash as a string or JSON in the wrong file format? If anyone can point me in the right direction towards extracting this data so I can work with it, I'd be eternally grateful!

Community
  • 1
  • 1
SoSimple
  • 681
  • 9
  • 24

1 Answers1

0

Each line of the text is a valid JSON, but putting them together, it's not valid.

You can turn each line into a Hash, and join them together:

students = []
file.each do |line|
  students << line
end
file.close

students.each {|e| e = JSON.parse(e) }

Now you can get the entire JSON by students.to_json.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267