在JSON响应中的嵌套数组中访问值
我有一个通过Web请求返回的多维JSON数组( http://www.coincap.io/history/365day/BTC )。 我想循环遍历第二个条目并检索它的嵌套值。
如果这是一个正常的数组,我会使用:
For Each item In response logic, logic, logic currentRow = currentRow + 1 Next
此Web请求返回一个JSON响应,其中包含3个条目:market_cap,price和volume。 我只是想通过response(1)
获取价格值。 price
中的每个条目都包含两个键0
和1
。
我会想象我能做到这一点
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")
。 两者都行不通。
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