【问题标题】:Trouble working with txt/json files使用 txt/json 文件时遇到问题
【发布时间】:2015-08-05 15:50:04
【问题描述】:

我在一家公司实习,得到了以下指示:

“您将在文本文件 (students.json) 中找到学生记录 - 一个 每行学生。编写程序计算平均成绩 班级。”

有问题的学生文件是一个带有 .txt 扩展名的要点,这是内容的一个示例:

{"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}

这是我第一次使用 JSON,所以我想我需要将它转换为哈希或其他东西,以便我可以更轻松地处理数据。

我尝试使用以下方法:

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

但我得到了错误:

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

我查看了this question,它表明我实际上没有 JSON,而是写为字符串的哈希。不幸运行

hash.eval(students)

只给我第一个学生记录,而不是其余的。我对我实际使用的内容有点困惑,它是纯文本文件,作为字符串的哈希还是错误文件格式的 JSON?如果有人能指出我提取这些数据的正确方向以便我可以使用它,我将永远感激不尽!

【问题讨论】:

    标签: ruby json file hash


    【解决方案1】:

    文本的每一行都是有效的 JSON,但将它们放在一起是无效的。

    您可以将每一行变成Hash,并将它们连接在一起:

    students = []
    file.each do |line|
      students << line
    end
    file.close
    
    students.each {|e| e = JSON.parse(e) }
    

    现在您可以通过students.to_json 获取整个 JSON。

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2020-09-10
      • 1970-01-01
      • 2021-08-25
      • 2014-05-17
      相关资源
      最近更新 更多