为什么Ruby无法解析本地JSON文件? [英] Why can Ruby not parse local JSON file?
问题描述
我在此处有一个相关问题,但我要发布另一个问题问题集中在问题的特定部分.
I have a related question here, but I'm posting another question to focus on a specific part of the problem.
目标:将脚本添加到我的Ruby应用中,该应用可以读取本地JSON文件,将其解析为Ruby哈希,然后访问其中的属性.
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.
系统:CentOS 7
System: CentOS 7
文件:本地保存的/tmp/valid.json
文件:
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
}
(该对象是从 Wikipedia上有关JSON的文章借来的,目的是确保我的问题不是无效的JSON.)
(That object borrowed from Wikipedia's article on JSON in an attempt to make sure that my problem isn't invalid JSON.)
代码:
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)
最后一行打印:
NoMethodError: undefined method `gsub' for #<Hash:0x0000000020951f
a8>
为什么Ruby无法解析此字符串?
Why can't Ruby parse this string?
推荐答案
问题在于您分配给 $ evm
的任何内容.错误消息:
The problem is something in whatever you have assigned to $evm
. The error message:
NoMethodError: undefined method `gsub' for #<Hash:>
表明您打电话时
$evm.log(:info, valid_ob)
log
方法正在尝试在 valid_ob
上调用 gsub
. log
最有可能只接受字符串,并且不对接收到的对象进行类型检查.
the log
method is attempting to call gsub
on valid_ob
. Most likely, log
is meant to accept only strings and does no type checking on the object it receives.
如果您需要一种简单的交互式方式来运行此Ruby代码而不使用此 $ evm
对象,只需在控制台中运行 irb
并开始输入您的Ruby代码用于解析JSON数据:
If you need a simple, interactive way to run this Ruby code without using this $evm
object, just run irb
in your console and start typing in your Ruby code for parsing the JSON data:
require 'json'
=> true
data = File.read('/tmp/valid.json')
data.class
=> String
hash = JSON.parse(data)
hash.class
=> Hash
hash
=> {"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"=>nil}
这篇关于为什么Ruby无法解析本地JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!