簡體   English   中英

使用Ruby解析JSON對象時出錯

[英]Getting error when parsing JSON object with Ruby

我試圖使用以下代碼解析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是一個哈希值,因此產生給塊的值是一個雙元素數組, [key,value] ,而我認為你假設你傳遞的只是值。 因此url是一個數組,所以當你要求url['#EXAMPLE_DOCUMENTATION_CALL']時,ruby不知道該怎么做

正確的做法取決於json的其余部分是什么樣的 - 如果你只想拔出那個網址,那么

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

應該做的伎倆。 如果你想要迭代commands那么

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

比單個塊參數是一個數組更容易使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM