VBA-JSON创建嵌套对象 [英] VBA-JSON Create nested objects

查看:135
本文介绍了VBA-JSON创建嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多示例,这些示例显示了如何使用VBA-JSON解析JSON字符串,但是我想知道如何使用该库从头开始创建JSON对象.

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.

我从开始:

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

这按预期工作.

但是,如果要创建一个嵌套对象,例如:

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

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

不输出预期值:{"new_key":[{"value": 1}, {"foo": "bar"}]}

这个库可以实现吗?还是有另一种方法?

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

谢谢

推荐答案

您可以在VBA中使用Dictionary and Collection. 之后,将它们转换为Json. 这是一个例子:

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

这是输出:

{"new_key":[{"value":1},{"foo":"bar"}]}

这篇关于VBA-JSON创建嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆