0

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user1642224
  • 61
  • 14
  • Can you add the full error message please. It seems that you missed the beginning. – Uzbekjon Apr 20 '16 at 19:54
  • @Uzbekjon It is printing entire json file but in the end it is showing up this error from /usr/lib/ruby/gems/1.8/gems/json-1.4.6/lib/json/common.rb:146:in `parse' from test.rb:9 – user1642224 Apr 20 '16 at 19:58
  • `parse` is implemented as a c extension, do you know if your current gem is compiled against your current version of ruby? – photoionized Apr 20 '16 at 21:12
  • Welcome to Stack Overflow. Please read "[ask]" and "[mcve]". Your JSON is valid. You say the filename is "Output.json" but the code shows you're trying to read "output.json". If the file is "Output.json" the code would have a different error. As is your problem can't be duplicated. Also, you tagged Ruby 1.9.2 and Ruby 1.8.7. Which are you using? You shouldn't use either as they're both extremely out-of-date. – the Tin Man Apr 20 '16 at 21:43

1 Answers1

0

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

Z-Bone
  • 1,534
  • 1
  • 10
  • 14