Read .json file

Hello guys,

I was trying to follow this tutorial to simply read a .json file but…

if I try:

require "json"
@file = File.open("/file_path/file.json")
@data = JSON.load(@file)

I get:

Error: #<JSON::ParserError: 814: unexpected token at '{
  "use_defaut":"true",
  "skp_path":"skp path here",
  "stl_path":"stl path here",
}'>

If I try:

require "json"
@file = File.read("/file_path/file.json")
@data = JSON.parse(@file)

I get:

Error: #<JSON::ParserError: 776: unexpected token at '{
  "use_defaut": "true",
  "skp_path": "skp path here",
  "stl_path": "stl path here",
}'>

the .json file is pretty simple:

{
  "use_defaut": "true",
  "skp_path": "skp path here",
  "stl_path": "stl path here",
}

Is something wrong on the .json file? I’ve tried some variations such double/simple quote, “:”, “=>”
nothing seems to work.

any advice?

thanks

There is a frivolous comma after the last data pair.

Might be an encoding issue. Your JSON should be UTF-8 encoded.

Start with a hash in Ruby and have the JSON lib create the string and write it to the file path.

json = Hash[
  "use_defaut", "true",
  "skp_path", "skp path here",
  "stl_path", "stl path here"
].to_json

File.write("/file_path/file.json", json)

And then try to read it back into a hash with Ruby.

Lastly, it is not necessary to use a @var for the string read from the file as you’ll just convert it to a hash anyway. Instance variables are for persistence and access across the scope of an instance object.

You’ll be doing this file read within a method and the string reference from the file will go out of scope when the method ends, so it’ll automatically get “cleaned up” by Ruby’s garbage collector.

2 Likes

thanks for ur quick reply Dan, gonna try it right now :slightly_smiling_face:

here is the generated json from ruby:

{"use_defaut":"true","skp_path":"skp path here","stl_path":"stl path here"}

It was just that comma! no errors now.

thanks a lot Dan :kissing_heart:

1 Like