6

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.

2
  • Please have a look on a link here
    – Asmita
    Aug 29, 2017 at 17:19
  • @asmitakalena I have already attached a link like that though thanks for prompt reply
    – John Ross
    Aug 29, 2017 at 17:27

2 Answers 2

23

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.

4
  • Thanks But I am newbie can you please help to write this. And +1 from side for your answer
    – John Ross
    Aug 29, 2017 at 17:17
  • 1
    Sorry, I actually can't. Writing a json parser shouldn't be done by a newbie because it's SUPER difficult. Just use the stdlib JSON. require "json" and then JSON.parse(json_string). Aug 29, 2017 at 17:19
  • I updated my example on how to parse json from a file using the standard library. Like I said, using JSON.parse is pure ruby, not an external gem. Aug 29, 2017 at 17:21
  • He meant as in: not having to import anything. Feb 19, 2020 at 15:39
2

JSON is part of the core Ruby library (as of 1.9.3 I believe). You just have to require it in your ruby application/file

require 'json'

## Then you can use JSON
JSON.parse("{}")
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.