反转JSON请求的输出

时间:2018-05-12 10:52:56

标签: json excel vba web-scraping

我编写了一个发送JSON请求的宏

Sub getPrices()

Dim strURL As String, strJSON As String, strTicker As String, strCurrency As String, strLength As String
Dim i As Integer
Dim i2 As Integer
Dim http As Object
Dim JSON As Object, Item As Object
Dim LastColumn As Long
Dim lastrow As Long
With ActiveSheet
    LastColumn = .Cells(9, .Columns.Count).End(xlToLeft).Column
    lastrow = .Cells(Rows.Count, 2).End(xlUp).Row
End With


For x = 10 To lastrow

strTicker = Cells(x, 2).Value
strCurrency = Cells(6, 2).Value
strLength = Cells(5, 2).Value
strURL = "https://min-api.cryptocompare.com/data/histoday?fsym=" & strTicker & "&tsym=" & strCurrency & "&limit=" & strLength & "&aggregate=3&e=CCCAGG"

Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", strURL, False
http.Send
strJSON = http.ResponseText
i = 3

Set JSON = JsonConverter.ParseJson(strJSON)
For Each Item In JSON("Data")
Cells(x, i).Value = Item("close")
i = i + 1

Next
Next

End Sub

此类JSON请求的示例是以下输出Example

宏以 Today 的数据位于 LastColumn 中的方式获取数据。 我在Excel中的数据库存在的问题是,所有免费数据都以相反的方式存储,其中 Today 可以在 A列中找到。我需要对齐数据。由于文件的大小,我理想情况下不想使用 MATCH-和INDEX -formula。如何以这样的方式重写我的宏,即从最近的数据生成数据 - >旧而不是旧 - >最近?

提前致谢,

1 个答案:

答案 0 :(得分:2)

您可以向后循环收集JSON("Data")。在这个简化的例子中:

<强>代码:

Option Explicit

Public Sub getPrices()

    Dim strURL As String, strJSON As String, http As Object, JSON As Object, item As Long

    strURL = "https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG"

    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open "GET", strURL, False
    http.Send
    strJSON = http.ResponseText

    Set JSON = JsonConverter.ParseJson(strJSON)

    For item = JSON("Data").Count To 1 Step -1   'JSON("Data")(item) <== dictionary
        Debug.Print JSON("Data")(item)("close")
    Next item

End Sub

示例输出:

Close prices in reverse

原始回复订单:

Original response