Trouble parsing JSON with vba

前端 未结 2 841
旧巷少年郎
旧巷少年郎 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:18

    The structure returned by JsonConverter.ParseJson function doesn't work such way. For your particular JSON it contains 3 levels: Root-level object has only one property reports, which contains second-level array, which in turn contains 6 third-level objects, having properties SavedName and SettingId. You are trying to get third-level's object property value from root-level object.

    First you need to get second-level array, then loop through it's elements, containing objects, and retrieve the SavedName properties' values of that objects. Here is the example:

    'Call for available reports
    
    Dim URLReporta As String
    Dim JSONa As Object
    Dim var As Object
    Dim rep As Variant
    Set myrequesta = CreateObject("winhttp.winhttprequest.5.1")
    URLReporta = ("https://secure.saashr.com:443/ta/rest/v1/reports?type=Saved&company%3shortname=" & Company)
    myrequesta.Open "GET", URLReporta, False
    myrequesta.setRequestHeader "Accept", "application/json"
    myrequesta.setRequestHeader "Authentication", "Bearer " & Token
    myrequesta.setRequestHeader "Content-Type", "application/json"
    myrequesta.Send
    Set JSONa = JsonConverter.ParseJson(myrequesta.responseText) ' root level object
    Set var = JSONa("reports") ' second level array
    For Each rep In var ' third level objects
        Debug.Print rep("SavedName") ' property "SavedName" value of current third level object
    Next
    

    Here is the output:

    If you want just to get the number of reports, then get the array and the number of elements in it:

    Debug.Print JSONa("reports").Count
    

提交回复
热议问题