从数组中提取元素

时间:2018-09-05 17:44:33

标签: json excel vba

您好,我之前也问过类似的问题:我有一个很大的JSON文件,但是我所需要的信息只是其中的一小部分。但是,该部分是“文本”。“大小”部分的二维数组。有什么办法可以循环每个数组并从已有的数组中获取数字?

{"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

非常感谢

1 个答案:

答案 0 :(得分: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结构中查看到集合集合的路径。 {}是字典,[]是集合。