Home » excel » excel – Inversing the output of a JSON-request

excel – Inversing the output of a JSON-request

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have written a macro that sends a JSON request

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

An example of such a JSON-request is the following output Example

The macro obtains the data in such a way that the data of Today is located in LastColumn.
The problem with my database in Excel is that all the complimentary data is storaged in the opposite way, where Today can be found in Column A. I need to align the data. Due to the size of the file, I, ideally, don’t want to use MATCH- and INDEX-formula’s. How can my macro be re-written in such a way that the data is produced from recent –> old instead of old –> recent?

Thanks in advance,

How to&Answers:

You could loop the collection, JSON("Data"), backwards. In this simplified example:

Code:

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

Example output:

Close prices in reverse

Original response order:

Original response

Answer:

I understand that what you want is to revert sort order in columns. For now the output starts from column 3.

Try changing:

i = 3

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

To:

Set JSON = JsonConverter.ParseJson(strJSON)
i = JSON("Data").Count + 2

For Each Item In JSON("Data")
Cells(x, i).Value = Item("close")
i = i - 1