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(JSON - Wikipedia) 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!