【问题标题】:Determine if Nested Key Exists in JSON Response - VBA确定 JSON 响应中是否存在嵌套键 - VBA
【发布时间】:2020-11-06 07:06:27
【问题描述】:

我在将 JSON 响应解析为 Excel 时遇到问题。问题是由于嵌套数组之一中的空值。当它存在时,我将值读入文件中没有问题,但我很难检查它是否存在。

我可以访问 field2 的 id 值,但是如果 field2 返回为 null,则会引发错误。我尝试了几种不同的方法来检查 field2 的 id 是否存在,但没有成功

         For Each Value In JsonObject("value")
        ws.Cells(rowindex, 21) = Value("value1")("id")
        For Each Item In Value("field1")
            If field1.Exists("field2")("id") Then
            'If field1.("field2").Exists("id") Then
                ws.Cells(rowindex, 22) = field1("field2")("id")
            End If
            ws.Cells(rowindex, 25) = field1("config")("id")
        Next
        rowindex = rowindex + 1
 Next

和 JSON 文件

    {
 "value": [
  {
   "value1": {
    "id": "123",
   },
   "field1": [
    {
     "config": {
      "id": "131",
     },
     "field2": {
      "id": "a594c0fc-6ddb-64da-b0e8-c544f2bbbe3e",
     }
    },{
     "config": {
      "id": "320",
     },
     "field2": {
      "id": "a594c0fc-6ddb-64da-b0e8-c544f2bbbe3e",
     }
    }]
  },{
   "value1": {
    "id": "456",
   },
   "field1": [
    {
     "config": {
      "id": "131",
     },
     "field2": null
    },{
     "config": {
      "id": "320",
     },
     "field2": null
    }]
  }],
 "count": 2
}

【问题讨论】:

    标签: arrays json excel vba


    【解决方案1】:

    类似这样的东西(未经测试):

    For Each Item In Value("field1")
        If item = "field2" Then
           If Not IsNull(item("field2")("id")) Then
              '....
           End If
        End If
    Next
    

    【讨论】:

    • 这让我走上了正轨。我只需要一个 If 语句 - If Not IsNull(field1("tester")) Then.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多