簡體   English   中英

使用 VBA Excel 從 JSON 字符串獲取數據

[英]get data from a JSON string with VBA Excel

我想從 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-String 中拆分信息。 我正在尋找一個解決方案,但我沒有找到任何可以與我的代碼一起使用的東西。

謝謝你幫助我!

您要返回的項目本身就是一個 json 字符串。 因此,要解析它,在 VBA 中,您需要創建另一個 json object。

例如:

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

只是為了展示 output:

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 代碼 所有都可以從用戶界面執行。

原始文件打開並解析為 json。

然后過濾內部 JSON 的結果; 將它和 output 拆分為一個表。

檢查Applied Steps window 以查看代碼的每個階段發生了什么。

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"

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM