我这里有一个示例JSON文件。
{
"tournaments": [{
"id": "sr:tournament:30",
"name": "Champions League",
"sport": {
"id": "sr:sport:6",
"name": "Handball"
},
"category": {
"id": "sr:category:73",
"name": "International"
},
"current_season": {
"id": "sr:season:41860",
"name": "Champions League 17\/18",
"start_date": "2017-09-02",
"end_date": "2018-05-28",
"year": "17\/18"
}
},
{
"id": "sr:tournament:57",
"name": "DHB Pokal",
"sport": {
"id": "sr:sport:6",
"name": "Handball"
},
"category": {
"id": "sr:category:53",
"name": "Germany",
"country_code": "DEU"
},
"current_season": {
"id": "sr:season:41782",
"name": "DHB Pokal 17\/18",
"start_date": "2017-08-18",
"end_date": "2018-05-31",
"year": "17\/18"
}
}]
}
我使用This解析了该文件。 我想获得锦标赛中的所有数据。 获得它的最佳方法是什么?
可以使用数组而不是字符串吗? JSons(1)(1)
而非JSons(1)("id")
?
这是我的代码
Set JSons = jsonObj("tournaments")
For Each json In JSons
For i = 1 To json.Count
Cells(a, b) = json(1)
b = b + 1
Next
a = a + 1
b = 1
Next
json(1)
返回一个空值,但是当我这样做时JSons(1)("id")
我得到了这个值。
答案 0 :(得分:0)
不知怎的,我得到了这些值。
Set JSons = jsonObj("tournaments")
For Each tournament In JSons
i=1
For each json in tournament
Cells(a, b) = jsons(i)(json)
b = b + 1
Next
a = a + 1
b = 1
Next
答案 1 :(得分:0)
您可以将JSON数据导入数组,如下面的示例代码所示。 将JSON.bas模块导入VBA项目以进行JSON处理。
Option Explicit
Sub Test()
' Put sourse JSON string to "\source.json" file, and save as ANSI or Unicode
Dim sJSONString As String
Dim vJSON As Variant
Dim sState As String
Dim aData()
Dim aHeader()
sJSONString = ReadTextFile(ThisWorkbook.Path & "\source.json", -2)
JSON.Parse sJSONString, vJSON, sState
vJSON = vJSON("tournaments")
JSON.ToArray vJSON, aData, aHeader
With Sheets(1)
.Cells.Delete
.Cells.WrapText = False
OutputArray .Cells(1, 1), aHeader
Output2DArray .Cells(2, 1), aData
.Columns.AutoFit
End With
End Sub
Sub OutputArray(oDstRng As Range, aCells As Variant)
With oDstRng
.Parent.Select
With .Resize(1, UBound(aCells) - LBound(aCells) + 1)
.NumberFormat = "@"
.Value = aCells
End With
End With
End Sub
Sub Output2DArray(oDstRng As Range, aCells As Variant)
With oDstRng
.Parent.Select
With .Resize( _
UBound(aCells, 1) - LBound(aCells, 1) + 1, _
UBound(aCells, 2) - LBound(aCells, 2) + 1)
.NumberFormat = "@"
.Value = aCells
End With
End With
End Sub
Function ReadTextFile(sPath As String, lFormat As Long) As String
' lFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath, 1, False, lFormat)
ReadTextFile = ""
If Not .AtEndOfStream Then ReadTextFile = .ReadAll
.Close
End With
End Function
我的输出如下: