Parsing JSON in Excel VBA

后端 未结 11 1060
长发绾君心
长发绾君心 2020-11-22 09:58

I have the same issue as in Excel VBA: Parsed JSON Object Loop but cannot find any solution. My JSON has nested objects so suggested solution like VBJSON and vba-json do not

11条回答
  •  广开言路
    2020-11-22 10:33

    Two small contributions to Codo's answer:

    ' "recursive" version of GetObjectProperty
    Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
        Dim names() As String
        Dim i As Integer
    
        names = Split(propertyName, ".")
    
        For i = 0 To UBound(names)
            Set JsonObject = ScriptEngine.Run("getProperty", JsonObject, names(i))
        Next
    
        Set GetObjectProperty = JsonObject
    End Function
    
    ' shortcut to object array
    Public Function GetObjectArrayProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object()
        Dim a() As Object
        Dim i As Integer
        Dim l As Integer
    
        Set JsonObject = GetObjectProperty(JsonObject, propertyName)
    
        l = GetProperty(JsonObject, "length") - 1
    
        ReDim a(l)
    
        For i = 0 To l
            Set a(i) = GetObjectProperty(JsonObject, CStr(i))
        Next
    
        GetObjectArrayProperty = a
    End Function
    

    So now I can do stuff like:

    Dim JsonObject As Object
    Dim Value() As Object
    Dim i As Integer
    Dim Total As Double
    
    Set JsonObject = DecodeJsonString(CStr(request.responseText))
    
    Value = GetObjectArrayProperty(JsonObject, "d.Data")
    
    For i = 0 To UBound(Value)
        Total = Total + Value(i).Amount
    Next
    

提交回复
热议问题