How to parse a JSON file in Ruby version 1.8.7

1.6k Views Asked by At

I have a file called Output.json:

[
  {
    "name": "krishna",
    "service": "postman",
    "host": "xxxxxx",
    "doing": [],
    "pool": "xxxxxx",
    "roleType": "yyyyy",
    "simple": true
  }
 ]

And this is my Test.rb file:

require 'rubygems'
require 'json'
require 'pp'

file = File.read('output.json')
data_hash= JSON.parse(file)
pp data_hash

When I try to run the script I get:

from /usr/lib/ruby/gems/1.8/gems/json-1.4.6/lib/json/common.rb:146:in `parse'

How do I print the value "krishna" when I call the name from the JSON file.

1

There are 1 best solutions below

0
Z-Bone On

Although I never tried version 1.8.7 (only 1.9.3 and higher)

I would assume your problem is that you aren't reading the file correctly. Try File.open instead

Try this:

file = File.open('output.json').read
data_hash = JSON.parse(file)
pp data_hash

as for printing the value krishna try this (after parsing):

puts data_hash['name']  # this outputs krishna

Good luck