使用VBA解析JSON(Access 2010)

时间:2016-06-16 04:43:28

标签: json vba web access

我需要使用下面的JSON文件更新MS-Access中的货币表:

{
"timestamp": 1465843806,
"base": "CAD",
"rates": {
"AED": 2.87198141,
"AFN": 54.21812828,
"ALL": 95.86530071,
"AMD": 374.48549935,
"ANG": 1.39861507
}
}

VBA代码如下:

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

上面的代码正常显示带有CAD的消息框,但我需要循环并捕获每个货币代码及其价值。我用什么语法来做这个?我可以提供函数Json()函数的代码,但没有看到上传它的方法。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果您使用此json解析器https://github.com/VBA-tools/VBA-JSON,请使用此代码

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

编辑: 您必须使用您想要执行的任何过程来修改debug.print。要从代码中使用它,请将此行放在MsgBox之后。

IterateDictionary Json

答案 1 :(得分:1)

您还可以字符串分析。例如,如果在费率的密钥对之后:

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

output