gpt4 book ai didi

ruby - 使用 Ruby 解析 JSON 对象时出错

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:54 24 4
gpt4 key购买 nike

我正在尝试使用以下代码在 ruby​​ 中解析出一个 JSON 对象:

def parseUrls(mFile, dirname)


f = File.open(File.join(dirname, mFile), 'r')
mF = f.read

json = JSON.parse(mF)

commands = json["commands"]
#puts commands

commands.each do |url|
puts url

mUrl = url["#EXAMPLE_DOCUMENTATION_CALL"]["URL"]
puts mUrl

#mString = String.new(DMMSERVER)
#i = mString.count(DMMSERVER)
#mUrl = mString.insert(i, tUrl)

#puts mUrl

end

但我一直收到这个错误:

    TypeError: can't convert String into Integer
[] at org/jruby/RubyArray.java:1348
parseUrls at ./fileParser.rb:48
each at org/jruby/RubyHash.java:1181
parseUrls at ./fileParser.rb:45
sendServiceRequest at testmdxservices.rb:31
getFile at testmdxservices.rb:20
each at org/jruby/RubyArray.java:1620
getFile at testmdxservices.rb:17
(root) at testmdxservices.rb:39

使用这个 JSON:

"commands":{
"#EXAMPLE_DOCUMENTATION_CALL":{
"TYPE" : "this is the server set we are comunicating with. example DMM, WDPRO, GOREG, ONESOURCE..etc if you don't know what these are ask some one from the team or look at QUICNY",
"URL" : "the full url of the call that will be turned into an http header",
"METHOD": "this is a flag that tells the user what kind of call in http to make. 0 = post, 1 = get, 2 = postmulti See int/uie_HttpRequests.ent for complete",
"BODY": "this is the body of the http call depending on the call type this will change or not exist often with things that need to be filled in about it.",
"NOTE": "comment section for information about how to use or what to expect when making this call."
},

谁能告诉我我做错了什么以及我该如何解决?

最佳答案

commands 是一个散列,因此产生给 block 的值是一个双元素数组,[key,value],而我认为你假设你是什么passed 只是值。因此 url 是一个数组,因此当您请求 url['#EXAMPLE_DOCUMENTATION_CALL']

时,ruby 不知道该怎么做

正确的做法取决于 json 的其余部分是什么样的 - 如果您只想提取那个 url,那么

commands['#EXAMPLE_DOCUMENTATION_CALL']['URL']

应该可以解决问题。如果您确实想遍历命令,那么

commands.each |key, value| do
...
end

比使用数组形式的单个 block 参数更容易使用

关于ruby - 使用 Ruby 解析 JSON 对象时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com