JsonConverter,错误对象,当密钥不存在时必需

时间:2018-12-09 14:46:00

标签: json vba rest api jsonconverter

我正在使用带有API的connect VBA,有时从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中获取“空”或“黄色”数据。

1 个答案:

答案 0 :(得分: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

输出: