JSON文本必须至少包含两个八位字节! (JSON :: ParserError)

时间:2016-05-04 23:38:02

标签: ruby json

我正在使用一个读取.json文件的Ruby脚本。

这是JSON文件:

{
  "feed.xml": "93d5b140dd2b4779edef0347ac835fb1",
  "index.html": "1cbe25936e392161bad6074d65acdd91",
  "md5.json": "655d7c1dbf83a271f348a50a44ba4f6a",
  "test.sh": "9be192b1b5a9978cb3623737156445fd",
  "index.html": "c064e204040cde216d494776fdcfb68f",
  "main.css": "21b13d87db2186d22720e8c881a78580",
  "welcome-to-jekyll.html": "01d7c7d66bdeecd9cd69feb5b4b4184d"
}

它完全有效,在尝试从中读取之前会检查它的存在。例如:

if File.file?("md5.json")
  puts "MD5s exists"
  mddigests = File.open("md5.json", "r")
  puts "MD5s" + mddigests.read
  items = JSON.parse(mddigests.read) <--- Where it all goes wrong.
  puts items["feed.xml"]

在此之前一切正常:

MD5s exists
MD5s{
  "feed.xml": "93d5b140dd2b4779edef0347ac835fb1",
  "index.html": "1cbe25936e392161bad6074d65acdd91",
  "md5.json": "655d7c1dbf83a271f348a50a44ba4f6a",
  "test.sh": "9be192b1b5a9978cb3623737156445fd",
  "index.html": "c064e204040cde216d494776fdcfb68f",
  "main.css": "21b13d87db2186d22720e8c881a78580",
  "welcome-to-jekyll.html": "01d7c7d66bdeecd9cd69feb5b4b4184d"
}
common.rb:156:in `initialize': A JSON text must at least contain two octets! (JSON::ParserError)

我搜索并尝试了很多不同的东西,但没有用。我很难过。谢谢!

1 个答案:

答案 0 :(得分:6)

您对read()的重复调用已全部出错。用变量read()替换第二次调用mddigests,一切都应该没问题。

此代码应该像您期望的那样工作:

if File.file?("md5.json")
  puts "MD5s exists"
  mddigests = File.open("md5.json", "r")
  digests = mddigests.read
  puts "MD5s" + digests
  items = JSON.parse(digests)   #<--- This should work now!
  puts items["feed.xml"]
end

原因是文件指针在第一个read()之后移动,而第二个read()移动到文件末尾,因此消息需要至少2个八位字节。