Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A JSON text must at least contain two octets! (JSON::ParserError)

Tags:

json

ruby

I'm working with a Ruby script that reads a .json file.

Here is the JSON file:

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

It is completely valid, and is checked for its existence before trying to read from it. Example:

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"]

Everything works up until that point:

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)

I've searched and tried a lot of different things, to no avail. I'm stumped. Thanks!

like image 913
Keaton Burleson Avatar asked May 04 '16 23:05

Keaton Burleson


1 Answers

You have a duplicate call to read() at the point that it all goes wrong. Replace the second call to read() with the variable mddigests and all should be fine.

This code should work like you'd expect:

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

The reason is that the file pointer is moved after the first read(), and by the second read(), it's at the end of file, hence the message requiring at least 2 octets.

like image 85
Michael Gaskill Avatar answered Nov 15 '22 08:11

Michael Gaskill