Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can parse JSON file by pure Ruby code without gem

I Have tried many ways and googled but everywhere i getting same way out, use json gem to parse a JSON file.

JSON.parse(string)

And couple of links are also using same stackoverflow Link

I wanted to achieve it by pure Ruby code without using any gem or rails help.

like image 433
John Ross Avatar asked Aug 29 '17 17:08

John Ross


1 Answers

JSON is in the stdlib, so using JSON.parse is pure ruby.

require "json"
json_from_file = File.read("myfile.json")
hash = JSON.parse(json_from_file)

or just JSON.parse("{}")

If you're looking to write your own JSON parser (good luck), but just keep in mind that it's just a string when read from a file. So, start by reading it in from your file

File.open("myfile.json") do |f|
  str = f.gets
  # start parsing
end

At this point you'll need to tokenize what you read, and start picking apart each bit. Read up on the json spec.

like image 148
jeremywoertink Avatar answered Sep 28 '22 18:09

jeremywoertink