【问题标题】:get data from a JSON string with VBA Excel使用 VBA Excel 从 JSON 字符串中获取数据
【发布时间】:2021-02-12 21:29:34
【问题描述】:

我想从 JSON 数组中的 JSON 字符串获取数据,并使用 VBA 将数据显示到 Excel 工作表中。我正在使用库(VBA-JSON v2.3.1 JsonConverter)

我有以下 JSON 对象

{

"deviceMessages":[
    {
        "messageSource":"cc",
        "externalSourceId":123,
        "messageId":"blabla",
        "internalDeviceId":66,
        "externalDeviceId":"123456789",
        "messageType":"UPLINK",
        "rawMessage":"{\"hello\":\"58\",\"hello\":\"hello\",\"name\":\"Peter\",\"ID\":\"12346789\",\"rxInfo\":[{\"GT_ID\":\"123456\",\"name2\":\"20202022022020\",\"time\":\"2021-02-12T03:51:43.050959Z\",\"rss\":12,\"SN\":8,\"location\":{\"latitude\":\"XX.XX\",\"longitude\":\"X.XXXXX\",\"altitude\":\"XXX\"}}],\"Info\":{\"frequency\":XXXXXXX,\"dr\":X},\"adr\":XXX,\"nt\":XXXX,\"port\":X,\"data\":\"XXXXXXXXXXXXXX\"}",
        "frame":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "createdAt":"2021-02-12T03:51:43.050Z",
        "Json":"{\"temperature\":22.6,\"humidity\":37,\"light\":1,\"motion\":1,\"co2\":640,\"vdd\":3.647}",
        "rs":12,
        "framePort":16,
        "nr":8.0,
        "dataRate":5,
        "counter":123456,
        "GT":[
            {
                "id":1324,
                "externalId":"123456789",
                "SourceId":1234,
                "companyId":66,
                "sn":"xxxxxx",
                "name":"hello",
                "latitude":"xxxxxxxx",
                "longitude":"xxxxxxx",
                "range":null,
                "status":"OK",
                "Note":null,
                "lastSeen":"2021-02-12T04:04:39Z"
            }
        ]
    }
]

 }

我使用 VBA 代码获取数据。这是有效的。

我的代码如下所示:

            Dim response2 As String
            Dim json1 As Object
            Dim ws2 As Worksheet
            strUrl = "https://xxxxxxxxxxxx/devices/11/"
            Set hReq = CreateObject("MSXML2.XMLHTTP")

        With hReq
                Set ws2 = Worksheets(3)
                .Open "GET", strUrl, False
                .SetRequestHeader "Authorization", "Bearer " & apitoken
                .Send
                response2 = hReq.responseText
                Set json1 = JsonConverter.ParseJson(response2)
                k = 2
                    For Each item In json1("deviceMessages")
                    ws2.Cells(k, 1) = item("createdAt")
                    ws2.Cells(k, 2) = item("dataFrame")
                    ws2.Cells(k, 3) = item("externalDeviceId")
                    ws2.Cells(k, 4) = item("externalSourceId")
                    ws2.Cells(k, 5) = item("internalDeviceId")
                    ws2.Cells(k, 6) = item("messageId")
                    ws2.Cells(k, 7) = item("messageType")
                    ws2.Cells(k, 8) = item("rawJson")
                    ws2.Cells(k, 9) = item("rawMessage")
                    k = k + 1
                    Next item
         End With

如何从“Json”获取数据:”

{\"temperature\":22.6,\"humidity\":37,\"light\":1,\"motion\":1,\"co2\":640,\"vdd\":3.647} ?

目前,我在一个单元格中获取信息,格式如下。

{"temperature":22.6,"humidity":37,"light":1,"motion":1,"co2":640,"vdd":3.647}

我想像这样将数据分成行和列:

我只是不知道如何从这个 JSON 字符串中拆分信息。我正在寻找解决方案,但没有找到任何可以与我的代码一起使用的解决方案。

谢谢你帮助我!

【问题讨论】:

    标签: json excel vba string


    【解决方案1】:

    您返回的项目本身就是一个 json 字符串。 所以要解析出来,在 VBA 中,你需要创建另一个 json 对象。

    例如:

    For Each Item In JSON("deviceMessages")
        Set JSON2 = parsejson(Item("Json"))
            Debug.Print "Temperature", JSON2("temperature")
            Debug.Print "Humidity", JSON2("humidity")
            'etc
    Next Item
    

    只是为了显示输出:

    Set JSON = parsejson(response2)
    
    For Each Item In JSON("deviceMessages")
        Set JSON2 = parsejson(Item("Json"))
        For Each key In JSON2
            Debug.Print key, JSON2(key)
        Next key
    Next Item
    

    =>

    temperature    22.6 
    humidity       37 
    light          1 
    motion         1 
    co2            640 
    vdd            3.647 
    
    

    当然,您也可以只使用 Power Query(在 Excel 2010+ 中可用)

    这是输出该数据的M-code。一切都可以从用户界面执行。

    原始文件被打开并解析为json。

    然后过滤内部 JSON 的结果;将其拆分并输出为表格。

    检查Applied Steps 窗口,看看代码的每个阶段发生了什么。

    let
        Source = Json.Document(File.Contents("C:\Users\ron\Desktop\text3.json")),
        deviceMessages = Source[deviceMessages],
        deviceMessages1 = deviceMessages{0},
        #"Converted to Table" = Record.ToTable(deviceMessages1),
        #"Filtered Rows" = Table.SelectRows(#"Converted to Table", each ([Name] = "Json")),
        #"Added Custom" = Table.AddColumn(#"Filtered Rows", "Custom", each Json.Document([Value])),
        Custom = #"Added Custom"{0}[Custom],
        #"Converted to Table1" = Record.ToTable(Custom),
        #"Transposed Table" = Table.Transpose(#"Converted to Table1"),
        #"Promoted Headers" = Table.PromoteHeaders(#"Transposed Table", [PromoteAllScalars=true]),
        #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"temperature", type number}, {"humidity", Int64.Type}, {"light", Int64.Type}, {"motion", Int64.Type}, {"co2", Int64.Type}, {"vdd", type number}})
    in
        #"Changed Type"
    

    【讨论】:

    • @Ivan1102 很高兴为您提供帮助。由于我的回答满足了您的问题,如果您能将其标记为已接受,我将不胜感激。您可以阅读What should I do when someone answers my question 了解更多信息。
    • 对不起,我以为我回答了你。我使用了第一个选项,这对我帮助很大。第二个选项我不知道如何付诸实践。我还没有使用过 PowerQuery。对我来说这是一个全新的领域。
    • @Ivan1102 是的,但我的回复左侧应该有一个复选标记。选中该标记表示接受答案。例如,您可能会在其中一个答案旁边看到带有绿色复选标记的其他主题。
    • 我没看过。我是 Stack Overflow 的新手。这是我的第二个问题。很抱歉给您带来不便。
    • @Ivan1102 在 VBA 中是可行的,只是需要更多步骤来设置表格然后填充它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2018-01-19
    相关资源
    最近更新 更多