首页 文章

JsonConverter,错误对象,当key doe不存在时需要

提问于
浏览
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”数据 .

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
    

    Output:

相关问题