0

我正在使用将 VBA 与 API 连接,有时从 API 返回的 JSON 具有动态密钥。像这样

json =[{"oeange":"good",}{"banana":{"color":"yellow"}},{"cat":"grumpy"}]

有时像这样

json = [{"oeange":"good",}{"banana":null},{"cat":"grumpy"}]

我试过了

for each item in json
 if item("banana").Exists("color") Then
    do something
End If

Next

它总是给出所需的错误对象。我看起来总是在寻找(“颜色”)

问题是如何从 json 中获取“null”或“yellow”的数据。

4

1 回答 1

1

您可以编写一个递归子程序来测试每个结构在 JSON 中的内容并进行适当处理。此外,您需要在开头移动尾随“,”的位置,以便它实际上分隔 JSON 中的项目。

所以在 A1 和 A2 我有以下内容:

[{"oeange":"good"},{"banana":{"color":"yellow"}},{"cat":"grumpy"}]
[{"oeange":"good"},{"banana":null},{"cat":"grumpy"}]

VBA:

Option Explicit
Public r As Long
Public Sub GetInfoFromSheet()
    Dim json As Object, jsonSource(), i As Long, ws As Worksheet, arr() As String
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    jsonSource = Application.Transpose(ws.Range("A1:A2").Value)

    For i = LBound(jsonSource) To UBound(jsonSource)
      Set json = JsonConverter.ParseJson(jsonSource(i))
      EmptyJSON json
    Next i
End Sub

Public Sub EmptyJSON(ByVal json As Object)
    Dim key As Variant, item As Object
    Select Case TypeName(json)
    Case "Dictionary"
        For Each key In json
            Select Case TypeName(json(key))
            Case "Dictionary"
                EmptyJSON json(key)
            Case Else
                r = r + 1
                With ThisWorkbook.Worksheets("Sheet1")
                    .Cells(r, 2) = key
                    .Cells(r, 3) = json(key)
                End With
            End Select
        Next
    Case "Collection"
        For Each item In json
            EmptyJSON item
        Next
    End Select
End Sub

输出:

于 2018-12-09T15:11:17.277 回答