Why can't Ruby parse local JSON file?

I see there are some related posts here and here, but they don’t seem to resolve my question.

Goal: Add script to my Ruby app which can read a local JSON file, parse it to a Ruby hash, and access the properties within it.

System: CentOS 7

File: Locally saved /tmp/valid.json file:

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    }
  ],
  "children": [],
  "spouse": null
}

(That object borrowed from Wikipedia’s article on JSON(https://en.wikipedia.org/wiki/JSON) in an attempt to make sure that my problem isn’t invalid JSON.)

Code:

require 'json'
data = File.read("/tmp/valid.json")
$evm.log(:info, data) #writes to log file, where I can see content of my JSON file
$evm.log(:info, "is data a hash ? ")
$evm.log(:info, data.is_a?(Hash).to_s) # prints false
$evm.log(:info, "is data a string? ")
$evm.log(:info, data.is_a?(String).to_s) # prints true
$evm.log(:info, "can I parse data?")
valid_ob = JSON.parse(data)
$evm.log(:info, "just parsed it, now print it")
$evm.log(:info, valid_ob)

That last line prints:

NoMethodError: undefined method `gsub' for #<Hash:0x0000000020951f
a8>

Why can’t Ruby parse this string? Thank you!

The error appears to be caused by the log call, not the parse.

JSON.parse returns a data structure (Hash): https://docs.ruby-lang.org/en/2.7.0/JSON.html#method-i-parse

whereas Logger’s log accepts a String or Exception as its message: https://docs.ruby-lang.org/en/2.7.0/Logger.html#method-i-add

(I got a different error message, so perhaps you are using a different logger library to Logger?)

@pcl You are right. The issue was the logging function I was calling. Thank you!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs