Extract JSON in Excel VBA

前端 未结 1 1191
名媛妹妹
名媛妹妹 2021-01-27 04:17

I want to parse stock quotes from the Robin Hood API via Excel VBA.

Say I want Amazon, which is https://api.robinhood.com/quotes/?symbols=AMZN.

Whic

相关标签:
1条回答
  • 2021-01-27 04:40

    Your json has an object called results. There could be, but isn't, multiple result objects. You have only one, so I think it's leading to confusion. Each result is going to get it's own entry in your jsonResponse dictionary. The ITEM in that dictionary will, itself, be a dictionary.

    The best way to deal with iterating through the dictionary in a dictionary is to declare a new dictionary, I'm calling att for "Attributes" and then fill that dictionary with each iteration through the jsonResponse dictionary. It will only iterate once though as you only have one result:

    Public Sub STOCKQUOTE()
    
        Dim http As Object
        Set http = CreateObject("MSXML2.XMLHTTP")
    
        Const sURL As String = "https://api.robinhood.com/quotes/?symbols=AMZN"
        http.Open "GET", sURL, False
        http.send
    
        Dim jsonResponse As Dictionary
        Set jsonResponse = JsonConverter.ParseJson(http.responseText)
    
        Dim att As Dictionary
    
        For Each att In jsonResponse("results")
         Debug.Print att("last_trade_price")
        Next att
    End Sub
    

    Alternatively, because you have only a single result, you could just refer to that result by it's index in the jsonResponse dictionary and then it's attribute you are after. This makes the code smaller, but if you ever get more than one result from your REST query it will be lost forever. No biggie though since you don't expect that to happen:

    Public Sub STOCKQUOTE()
    
        Dim http As Object
        Set http = CreateObject("MSXML2.XMLHTTP")
    
        Const sURL As String = "https://api.robinhood.com/quotes/?symbols=AMZN"
        http.Open "GET", sURL, False
        http.send
    
        Dim jsonResponse As Dictionary
        Set jsonResponse = JsonConverter.ParseJson(http.responseText)
    
        MsgBox (jsonResponse("results")(1)("last_trade_price"))
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题