Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

Does not seem to do it...it will map the key to a string, and gives an error when trying to access individual values as Json("new_key")("value") – drec4s Feb 28, 2018 at 15:47

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"}]}
Set Json = JsonConverter.ParseJson("{}")
'Set Json = CreateObject("scripting.dictionary")
Json.Add "new_key", CreateObject("scripting.dictionary")
Json("new_key")("value") = 1
Json("new_key")("foo") = "bar"
                I just noticed I maybe mis-read your required output: @xuanhai266's solution is a better match.
– Tim Williams
                Feb 28, 2018 at 18:27
                Yes, but in fact all I really wanted was to understand the creation of a new nested key, and this line Json.Add "new_key", CreateObject("scripting.dictionary") did the trick.
– drec4s
                Feb 28, 2018 at 21:25
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.