在读取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就读不出来了。