Reputation: 23513
I am trying to parse out a JSON object in ruby using the following code:
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
But I keep getting this error:
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
Using this 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."
},
Can anyone tell me what I am doing wrong and how I can fix it?
Upvotes: 1
Views: 628
Reputation: 84182
commands
is a hash so that value yielded to the block is a two element array, [key,value]
, whereas I think you are assuming that what you are passed is the value only. Therefore url
is an array so ruby doesn't know what to do when you ask for url['#EXAMPLE_DOCUMENTATION_CALL']
The right thing to do depends on what the rest of the json looks like - if you just want to pull out that one url, then
commands['#EXAMPLE_DOCUMENTATION_CALL']['URL']
should do the trick. If you do want to iterate through commands
then
commands.each |key, value| do
...
end
is easier to use than having a single block argument that is an array
Upvotes: 3