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
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