从数组中提取元素

问题描述 投票:0回答:1

嗨我之前问了类似的问题:我有一个大的JSON文件,但我需要的信息只是其中的一小部分。但是,那个部分是来自“text”。“size”部分的二维数组。我能以任何方式循环每个数组并从我已经获得的数字中得到数字吗?

{"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": [[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]], "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } } }

我被某人教过(谢谢!)使用以下代码

Option Explicit
Public Sub GetInfo()
    Dim strJSON As String, json As Object, rowNumber As Long
    Application.ScreenUpdating = False
    Const PATH As String = "C:\Users\User\Desktop\test.JSON"
    strJSON = GetJSONFromFile(PATH)
    Set json = JsonConverter.ParseJson(strJSON)
    Set json = json("widget")("text")
    Dim key As Variant
    With ThisWorkbook.Worksheets("Sheet1")
        For Each key In json
            rowNumber = rowNumber + 1
            .Cells(rowNumber, 1) = key
            .Cells(rowNumber, 2) = json(key)
        Next key
    End With
    Application.ScreenUpdating = True
End Sub

非常感谢

json excel vba
1个回答
1
投票

看到预期的产出会有所帮助。如果您只是在JsonConverter.ParseJson(strJSON)("widget")("text")("size")返回的集合集合中的项目之后,则以下将清空它们。

Option Explicit
Public Sub GetInfo()
    Dim strJSON As String, json As Object, rowNumber As Long, i As Long, j As Long
    Const PATH As String = "C:\Users\User\Desktop\test.JSON"
    strJSON = GetJSONFromFile(PATH)
    Set json = JsonConverter.ParseJson(strJSON)("widget")("text")("size") '<collection of collections

    With ThisWorkbook.Worksheets("Sheet1")
        For i = 1 To json.Count
            For j = 1 To json(i).Count
                rowNumber = rowNumber + 1
                .Cells(rowNumber, 1) = json(i)(j)
            Next
        Next
    End With
End Sub
Public Function GetJSONFromFile(ByVal PATH As String) As String
    Dim fso As Object, f As Object, outputString As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(PATH)

    Do Until f.AtEndOfStream
        outputString = f.ReadAll()
    Loop
    f.Close

    GetJSONFromFile = outputString
End Function

JSON结构:

您可以在下面的JSON结构中查看到集合集合的路径。 {}是字典,[]是收藏品。

© www.soinside.com 2019 - 2024. All rights reserved.