1

次のコードを使用して、ルビーで 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."
        },

誰が私が間違っているのか、どうすれば修正できるのか教えてもらえますか?

4

1 に答える 1

3

commandsはハッシュであるため、ブロックに生成される値は 2 つの要素の配列に[key,value]なりますが、渡されるのは値のみであると想定していると思います。したがってurl、配列なので、Ruby は、あなたが要求したときに何をすべきかわかりません。url['#EXAMPLE_DOCUMENTATION_CALL']

正しいことは、json の残りの部分がどのように見えるかによって異なります。その URL を 1 つだけ取り出したい場合は、

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

トリックを行う必要があります。繰り返したい場合はcommands

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

配列である単一のブロック引数を持つよりも使いやすい

于 2012-10-08T20:44:35.667 に答える