问题
I need to update a currency table in MS-Access with a JSON file below:
{
"timestamp": 1465843806,
"base": "CAD",
"rates": {
"AED": 2.87198141,
"AFN": 54.21812828,
"ALL": 95.86530071,
"AMD": 374.48549935,
"ANG": 1.39861507
}
}
The VBA code is as follows:
Private Sub cmdJsonTest_Click()
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", "https://website.org/api/latest.json?base=CAD"
MyRequest.send
' MsgBox MyRequest.ResponseText
Dim Json As Object
Set Json = JsonConverter.ParseJson(MyRequest.ResponseText)
MsgBox Json("base")
End Sub
The above code works correctly displaying a message box with CAD but I need to loop through and capture each currency code along with it's rate value. What syntax do I use to do this? I can provide the code for the function Json() function but did not see a way to upload it. Any assistance would be appreciated.
回答1:
If you are using this json parser https://github.com/VBA-tools/VBA-JSON, use this code
Private Sub IterateDictionary(poDict As Dictionary)
Dim key As Variant
For Each key In poDict.Keys()
If TypeName(poDict(key)) = "Dictionary" Then
Debug.Print key
IterateDictionary poDict(key)
Else
Debug.Print key, poDict(key)
End If
Next
End Sub
EDIT: You have to modify the debug.print with whatever process you want to do. To use this from your code put this line after MsgBox.
IterateDictionary Json
回答2:
You could also string parse. For example, if after key pairs for the rates:
Option Explicit
Public Sub GetValues()
Dim s As String, rates(), i As Long
s = "{""timestamp"": 1465843806,""base"": ""CAD"",""rates"": {""AED"": 2.87198141,""AFN"": 54.21812828,""ALL"": 95.86530071,""AMD"": 374.48549935,""ANG"": 1.39861507}}"
rates = Array("AED", "AFN", "ALL", "AMD", "ANG")
For i = LBound(rates) To UBound(rates)
Debug.Print rates(i) & ":" & GetRate(s, rates(i))
Next i
End Sub
Public Function GetRate(ByVal s As String, ByVal delimiter As String) As String
GetRate = Replace(Split(Split(s, delimiter & Chr$(34) & Chr$(58))(1), Chr$(44))(0), Chr$(125), vbNullString)
End Function
来源:https://stackoverflow.com/questions/37850036/parse-json-with-vba-access-2010