Trouble parsing JSON with vba

前端 未结 2 839
旧巷少年郎
旧巷少年郎 2021-01-16 15:24

I can get what appears to be a valid JSON string from a web query, however, I cannot set items correctly for the life of me. Need to confirm that I\'m not losing m

2条回答
  •  再見小時候
    2021-01-16 16:05

    JSON objects can be thought of as a collection of dictionaries. So you have to walk through the inner values such as SavedName to retrieve whole dictionary objects (all SavedName values) or specific string values at indexed locations (one SavedName value):

    Public Sub GetJSONRequest()
        Dim jsonStr As String
    
        jsonStr = "{" _
             & "     ""reports"": [{" _
             & "         ""SavedName"": ""This Year""," _
             & "         ""SettingId"": 18959322" _
             & "     }, {" _
             & "         ""SavedName"": ""Time Off Requests""," _
             & "         ""SettingId"": 18960210" _
             & "     }, {" _
             & "         ""SavedName"": ""Calc Hours Summary""," _
             & "         ""SettingId"": 18960209" _
             & "     }, {" _
             & "         ""SavedName"": ""roster""," _
             & "         ""SettingId"": 18960211" _
             & "     }, {" _
             & "         ""SavedName"": ""E/D/T""," _
             & "         ""SettingId"": 18823042" _
             & "     }, {" _
             & "         ""SavedName"": ""TestZDR""," _
             & "         ""SettingId"": 18957188" _
             & "  }]" _
             & "  }"
    
        Dim JSONa As Object, element As Object, e As Variant, i As Variant, var As Variant
    
        Set JSONa = ParseJson(jsonStr)
    
        ' DICTIONARY OBJECT
        Set element = CreateObject("Scripting.Dictionary")
        Set element = JSONa("reports")
    
        ' OUTER DICTIONARY
        For Each e In element
            ' INNER COLLECTION OF DICTIONARIES
            For Each i In e
                Debug.Print i & " " & e(i)
            Next i
        Next e            
    
        ' STRING VALUE OF FIRST SAVEDNAME VALUE
        var = JSONa("reports")(1)("SavedName")
        Debug.Print var
    
        Set element = Nothing
        Set JSONa = Nothing
    End Sub
    

    Output

    SavedName This Year
    SettingId 18959322
    SavedName Time Off Requests
    SettingId 18960210
    SavedName Calc Hours Summary
    SettingId 18960209
    SavedName roster
    SettingId 18960211
    SavedName E/D/T
    SettingId 18823042
    SavedName TestZDR
    SettingId 18957188
    This Year
    

提交回复
热议问题