VBA-JSON Create nested objects

前端 未结 2 1336
情话喂你
情话喂你 2021-01-07 01:15

I have seen a lot of examples showing how to parse json strings with VBA-JSON, however I would like to know how to create a JSON object from scratch using this library.

相关标签:
2条回答
  • 2021-01-07 01:40

    You can use Dictionary and Collection in VBA. After that convert them to Json. This is an example:

    Sub test()
        Dim c As Collection
        Dim d As Dictionary
        Dim e As Dictionary
        Dim f As Dictionary
        Dim json As String
    
        Set c = New Collection
        Set d = New Dictionary
        Set e = New Dictionary
        Set f = New Dictionary
    
        d.Add "value", 1
        e.Add "foo", "bar"
        c.Add d
        c.Add e
        f.Add "new_key", c
    
        json = JsonConverter.ConvertToJson(ByVal f)
    
        Debug.Print json
    End Sub
    

    And this is output:

    {"new_key":[{"value":1},{"foo":"bar"}]}
    
    0 讨论(0)
  • 2021-01-07 01:45

    Something like this:

    Set Json = JsonConverter.ParseJson("{}")
    'or
    'Set Json = CreateObject("scripting.dictionary")
    
    Json.Add "new_key", CreateObject("scripting.dictionary")
    Json("new_key")("value") = 1
    Json("new_key")("foo") = "bar"
    
    0 讨论(0)
提交回复
热议问题