I have a related question here, but I’m posting another question to focus on a specific part of the problem.
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 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?
2
Answers
The problem is something in whatever you have assigned to
$evm
. The error message:indicates that when you call
the
log
method is attempting to callgsub
onvalid_ob
. Most likely,log
is meant to accept only strings and does no type checking on the object it receives.If you need a simple, interactive way to run this Ruby code without using this
$evm
object, just runirb
in your console and start typing in your Ruby code for parsing the JSON data:Have you tried printing the object normally, instead of using "$evm.log"? JSON.parse returns a hash, and it seems as though your logger is attempting to run a non-existent gsub method on it.