Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA-JSON Create nested objects

Tags:

json

excel

vba

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.

I have started with:

Set Json = JsonConverter.ParseJson("{}")
Json("key") = "value"

And this works as expected.

However, if I want to create a nested object, for example:

Json("new_key")(1)("value") = 1
Json("new_key")(2)("foo") = "bar"

Does not output the expected: {"new_key":[{"value": 1}, {"foo": "bar"}]}

Is this possible to achieve with this library? Or is there another way to do it?

Thanks

like image 886
drec4s Avatar asked May 14 '26 00:05

drec4s


1 Answers

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"}]}
like image 99
xuanhai266 Avatar answered May 15 '26 13:05

xuanhai266