2017-06-08 96 views
0

我有一個通過web請求返回的多維JSON數組(http://www.coincap.io/history/365day/BTC)。我想遍歷第二個條目並檢索它的嵌套值。訪問JSON響應中的嵌套數組中的值

如果這是一個正常的陣列,我會使用:

For Each item In response 
    logic, logic, logic 

    currentRow = currentRow + 1 
Next 

這個web請求返回的JSON響應與3項:market_cap,價格,和體積。我只想循環通過response(1)並獲得價格值。 price中的每個條目都包含兩個密鑰01

我會想象我可以做

For Each item in response(1) 
    Cells(currentRow, 1).Value = item(0) 
    Cells(currentRow, 2).Value = item(1) 

    currentRow = currentRow + 1 
Next 

我也認爲For Each item in response("price")做到這一點。兩者都不起作用。

+0

請準確顯示/描述你如何到達'response'對象。你在使用JSON解析庫/類嗎?如果是,哪一個?如果沒有,那麼......?如果你提供一套工作的代碼來讓他們至少達到你的要求,那麼民衆就會更容易幫助你。 –

回答

1
Sub Tester() 

    Dim json As String 
    Dim sc As Object 
    Dim o, n, i, p 

    Set sc = CreateObject("scriptcontrol") 
    sc.Language = "JScript" 

    json = HttpGet("http://www.coincap.io/history/365day/BTC") 

    sc.Eval "var obj=(" & json & ")" 'evaluate the json response 
    'add a couple of accessor functions 
    sc.AddCode "function numPrices(){return obj.price.length;}" 
    sc.AddCode "function getPrice(i){return obj.price[i];}" 

    n = sc.Run("numPrices") 
    For i = 0 To n - 1 
     p = Split(sc.Run("getPrice", i), ",") 
     Debug.Print i, p(0), p(1) 
    Next i 

End Sub 

Function HttpGet(url As String) As String 
    Dim oHTML As Object 
    Set oHTML = CreateObject("Microsoft.XMLHTTP") 
    With oHTML 
     .Open "GET", url, False 
     .send 
     HttpGet = .responsetext 
    End With 
End Function