通过 VBA-JSON 库解析 JSON 时出错



我收到一个

运行时错误 13 类型不匹配

Cells(i,1).value=item("fp")行.

不知道为什么无法选择该项目。正如您可以观察到的 json 文件,它的"fp"值为"042018">

Sub Jsonread()
Dim FSO As New FileSystemObject
Dim JsonTS As TextStream
Dim jsonText As String
Dim jsonObject As Object
Dim item As variant
Set JsonTS = FSO.OpenTextFile("C:UsersAbdretoffline_others.json", ForReading)
jsonText = JsonTS.ReadAll
JsonTS.Close
Dim i As Long
Set jsonObject = JsonConverter.ParseJson(jsonText)
i = 3
For Each item In jsonObject
Cells(i, 1) = item("fp")
Cells(i, 2) = item("sply_ty")
i = i + 1
Next
End Sub

json 的摘录如下所示

{
"name": "Flip",
"fp": "042018",
"filing_typ": "M",
"gt": 0,
"cur_gt": 0,
"b2cs": [
{
"csamt": 0,
"sply_ty": "INTRA"
},

首先,您显示的 JSON 无效。它以,结尾,但必须是一个]},而不是逗号才能使其成为有效的 JSON 示例:

{
"name": "Flip",
"fp": "042018",
"filing_typ": "M",
"gt": 0,
"cur_gt": 0,
"b2cs": [{
"csamt": 0,
"sply_ty": "INTRA"
}]
}

代码1:可与以下代码一起使用的有效 JSON 示例。

确保仅将有效的 JSON 数据放入解析器。如果您提供无效数据,解析器将挂起或在最佳情况下抛出错误。

Option Explicit
Public Sub Jsonread()
Dim FSO As New FileSystemObject
Dim JsonTS As TextStream
Set JsonTS = FSO.OpenTextFile("C:UsersAbdretoffline_others.json", ForReading)
Dim jsonText As String
jsonText = JsonTS.ReadAll
JsonTS.Close
Dim jsonObject As Object
Set jsonObject = JsonConverter.ParseJson(jsonText)
Debug.Print jsonObject("fp")
Debug.Print jsonObject("b2cs")(1)("sply_ty")
End Sub

代码2:用于从代码 1 解析 JSON 的 VBA 代码。

解释:

jsonObject("b2cs")表示以下内容:

"b2cs": [{
"csamt": 0,
"sply_ty": "INTRA"
}]

然后jsonObject("b2cs")(1)将获得[]括号中的第一项,它代表以下内容:

{
"csamt": 0,
"sply_ty": "INTRA"
}

最后jsonObject("b2cs")(1)("sply_ty")您正在寻找的项目,它将产生:

042018
INTRA

最新更新