【问题标题】:Parsing JSON in Excel VBA and access array by key在 Excel VBA 中解析 JSON 并按键访问数组
【发布时间】:2020-05-25 09:55:27
【问题描述】:

我正在尝试使用 Excel VBA 从网站 (Link) 中抓取内容。这是来自服务器 (Link) 的 .json 响应:

{
  "TopicDetails": {
    "type": 0,
    "ccm2Id": 31088568,
    "cftId": 0,
    "identifier": "FETOPEN-01-2018-2019-2020",
    "title": "FET-Open Challenging Current Thinking",
    "actions": [
      {
        "status": {
          "id": 31094502,
          "abbreviation": "Open",
          "description": "Open"
        },
        "types": [
          "RIA Research and Innovation action"
        ],
        "plannedOpeningDate": "07 November 2017",
        "submissionProcedure": {
          "id": 31094504,
          "abbreviation": "multiple cut-off",
          "description": "multiple cut-off"
        },
        "deadlineDates": [
          "16 May 2018",
          "24 January 2019",
          "18 September 2019",
          "03 June 2020"
        ]
      }
    ]
  }
}

为此,编写了一个宏,效果很好。但是,我在访问存储在块“操作”中的信息(尤其是具有关键“类型”和最新截止日期的数据)时遇到了困难。错误消息是“下标超出范围”。

这是我的代码的相关部分:

Private Sub getJson()

Dim http As Object
Dim JSON As Object
Dim response As String
Dim url As String
Dim id As String
Dim oTarget As Object

id = "FETOPEN-01-2018-2019-2020"
url = "https://ec.europa.eu/info/funding-tenders/opportunities/data/topicDetails/" & LCase(id) & ".json?lang=en"

Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", url, False
http.send
response = http.responseText

Set JSON = JsonConverter.ParseJson(response)

'--- WORKS ---
Cells(5, 11).Value = JSON("TopicDetails")("title")

'--- DOESN'T WORK ---
'--- Test 1 ---
Cells(5, 17).Value = JSON("TopicDetails")("actions")("types")
'--- Test 2 ---
Cells(5, 18).Value = JSON("TopicDetails")("actions")(0)
'--- Test 3 ---
Cells(5, 19).Value = JSON("TopicDetails")("actions")(0)("types")
'--- Test 4 ---
Set oTarget = JSON("TopicDetails")("actions")
With oTarget
    Cells(5, 18).Value = .item(0).item(0)
End With

End Sub

在尝试处理“actions”数组的元素时,我发现以下代码提供了 1 作为答案(这是有道理的):

Set oTarget = JSON("TopicDetails")("actions")
Cells(5, 18).Value = oTarget.count

同时,在尝试接近数组的下一级时,以下代码提供了一个错误(“下标超出范围”),而不是预期的 5:

Set oTarget = JSON("TopicDetails")("actions")(0)
Cells(5, 18).Value = oTarget.count

如何提取信息“RIA Research and Innovation action”(具有关键的“类型”)和最晚截止日期 2020 年 6 月 3 日(具有关键的“deadlineDates”)?

提前感谢您!非常感谢任何帮助!

马克西姆

【问题讨论】:

    标签: json vba web-scraping jsonconverter


    【解决方案1】:

    这是因为数据类型“类型”是数组。

    根据 VBA-JSON 示例https://github.com/VBA-tools/VBA-JSON,数组索引从 1 开始。

    试试这个:

    Cells(5, 19).Value = JSON("TopicDetails")("actions")(1)("types")(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      相关资源
      最近更新 更多