1

I would like to get data from a JSON-String, which is in a JSON-Array, with VBA to display the data into an Excel-Worksheet. I'm using the library (VBA-JSON v2.3.1 JsonConverter)

I have the following JSON-Object

{

"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"
            }
        ]
    }
]

 }

I got the data with a VBA-code. That is working.

My code looks like this:

            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

How can I get the data from "Json":"

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

For now, I get the information in a cell with the following format.

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

I would like to split the data into rows and columns like this:

enter image description here

I just don't know how to split the information from this JSON-String. I was searching for a solution, but I didn't find anything, that could work with my code.

Thanks for helping me!

1 Answer 1

3

The item you are returning is, itself, a json string. So to parse it out, in VBA, you need to create another json object.

eg:

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

And just to show the 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 

Of course, you could also just use Power Query (available in Excel 2010+)

Here is M-code that outputs that data. All can be executed from the User Interface.

The original file is opened and parsed as a json.

Then filter on the result for the internal JSON; split that and output as a table.

Examine the Applied Steps window to see what happens at each stage of the code.

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"

enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

I'm sorry, I thought I answered you. I have used the first option, which helped me a lot. The second option I don't know how to put into practice. I have not used PowerQuery yet. It is a totally new field for me.
@Ivan1102 Yes, but there should be a check mark to the left of my response. Accepting the answer is signified by checking that mark. You may see other threads with a green check mark next to one of the answers, as an example.
I had not seen it. I am new in Stack Overflow. This was my second question. Sorry for the inconvenience.
@Ivan1102 So far as the PQ solution, you could navigate to Get Data from a JSON and then open the file. (or you could just paste the code into a blank query, changing the file name to whatever the real file name is). It might be worthwhile to play around with it.
@Ivan1102 It is doable in VBA, just requires more steps to set up the table and then populate it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.