Excel VBA - 如何将多数组JSON中的数据转换为列

时间:2016-11-07 07:32:09

标签: json excel vba

我找到了解析JSON的解决方案,它适用于所提供的示例:

以下是代码:

    Sub Test()
    Dim jsonText As String
    Dim jsonObj As Dictionary
    Dim jsonRows As Collection
    Dim jsonRow As Collection
    Dim ws As Worksheet
    Dim currentRow As Long
    Dim startColumn As Long
    Dim i As Long

    Set ws = Worksheets("VIEW")

    'Create a real JSON object
    jsonText = ws.Range("A1").Value

    'Parse it
    Set jsonObj = JSON.parse(jsonText)

    'Get the rows collection
    Set jsonRows = jsonObj("rows")

    'Set the starting row where to put the values
    currentRow = 1

    'First column where to put the values
    startColumn = 2 'B

    'Loop through all the values received
    For Each jsonRow In jsonRows
        'Now loop through all the items in this row
        For i = 1 To jsonRow.Count
            ws.Cells(currentRow, startColumn + i - 1).Value = jsonRow(i)
        Next i

        'Increment the row to the next one
        currentRow = currentRow + 1
    Next jsonRow
End Sub

正在运行的JSON:

{"rows":[["20120604", "ABC", "89"],["20120604", "BCD", "120"],["20120604", "CDE","239"]]}

但是我需要解析具有如下结构的JSON:

 [{"Id":"2604","Price": 520.4, "State": true},{"Id":"2605","Price": 322.8, "State": false},{"Id":"2619","Price": 104.7, "State": true},{"Id":"2628","Price": 182.2, "State": true}]

这意味着,在这种情况下,它应该是3列(Id,价格,状态)和4行。

应该很容易,但我只是一个新手......

1 个答案:

答案 0 :(得分:1)

应该是这样的:

Dim jsonRows As Collection
Dim jsonRow As Dictionary 

'...

'Parse it
Set jsonRows = JSON.parse(jsonText)

'Set the starting row where to put the values
currentRow = 1

'First column where to put the values
startColumn = 2 'B

'Loop through all the values received
For Each jsonRow In jsonRows
    'Now set all the values in this row

    ws.Cells(currentRow, startColumn).Value = jsonRow("Id")
    ws.Cells(currentRow, startColumn + 1).Value = jsonRow("Price")
    ws.Cells(currentRow, startColumn + 2).Value = jsonRow("State")

    'Increment the row to the next one
    currentRow = currentRow + 1
Next jsonRow