JSON数列读取

在读取JSON文件时,有时返回的是多个JSON文件数列,出现这样的情况时,如果是符合JSON文件格式则可以直接读取,如果不是,则需要进行补全。例如

{"num": 1,"title": "标题1"},{"num": 2,"title": "标题2"},{"num": 3,"title": "标题3"}

并不是完整的JSON格式文件,可以加头加尾成标准JSON文件,如下:

{"item": [ {"num": 1,"title": "标题1"}, {"num": 2, "title": "标题2"},{"num": 3,"title": "标题3"}]}

如此则可以直接读取。
附上VB读取JSON代码,

Function JSONValue(ByVal JSONCode As String, ByVal JSONPath As String) As Variant
Dim ScriptObj As Object
Set ScriptObj = CreateObject("MSScriptControl.ScriptControl")
ScriptObj.AllowUI = True
ScriptObj.Language = "JavaScript"
ScriptObj.AddCode "var data = " & JSONCode & ";"
'Debug.Print ScriptObj.eval("data.item[0].time")
JSONValue = ScriptObj.eval("data." & JSONPath)
Set ScriptObj = Nothing
End Function

Sub test()
Dim i As Integer
Dim JSONString As String
JSONString = " {""item"": [ {""num"": 1,""title"": ""标题1""}, {""num"": 2, ""title"": ""标题2""},{""num"": 3,""title"": ""标题3""}]}"
'为VB中的引号字符转义,上面用两个引号表示引号
For i = 0 To JSONValue(JSONString, "item.length") - 1 '查看字符串长度
    Debug.Print JSONValue(JSONString, "item[" & i & "].num")
    Debug.Print JSONValue(JSONString, "item[" & i & "].title")
Next i
End Sub
监视窗口查看层级结构

还要注意,length不能大写,写成Length就读不出来了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容