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

Kea*_*son 5 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"
}
Run Code Online (Sandbox Code Playgroud)

它是完全有效的,并在尝试从中读取之前检查它的存在.例:

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"]
Run Code Online (Sandbox Code Playgroud)

在此之前一切正常:

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)
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*ill 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
Run Code Online (Sandbox Code Playgroud)

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