下面的示例...从解析的JSON字符串循环对象返回错误"对象不支持此属性或方法".任何人都可以建议如何使这项工作?非常感谢(我在这里问了6个小时寻找答案).
用于将JSON字符串解析为对象的函数(这可以正常工作).
Function jsonDecode(jsonString As Variant)
Set sc = CreateObject("ScriptControl"): sc.Language = "JScript"
Set jsonDecode = sc.Eval("(" + jsonString + ")")
End Function
Run Code Online (Sandbox Code Playgroud)
循环解析对象将返回错误"对象不支持此属性或方法".
Sub TestJsonParsing()
Dim arr As Object 'Parse the json array into here
Dim jsonString As String
'This works fine
jsonString = "{'key1':'value1','key2':'value2'}"
Set arr = jsonDecode(jsonString)
MsgBox arr.key1 'Works (as long as I know the key name)
'But this loop doesn't work - what am I doing wrong?
For Each keyName In arr.keys 'Excel errors out …Run Code Online (Sandbox Code Playgroud) 我有一个像下面这样的json:
{"sentences":[{"trans":"something ru","orig":"english word","translit":"Angliyskoye slovo","src_translit":""}], "src":"en","server_time":69}
Run Code Online (Sandbox Code Playgroud)
并解析它:
Function jsonDecode(jsonString As Variant)
Set sc = CreateObject("ScriptControl"): sc.Language = "JScript"
Set jsonDecode = sc.Eval("(" + jsonString + ")")
End Function
Set arr = jsonDecode(txt)
Run Code Online (Sandbox Code Playgroud)
结果 arr包含如下所示的值(在Watches中检查):
arr
- sentences (type: Variant/Object/JScriptTypeInfo)
- 0 (type: Variant/Object/JScriptTypeInfo)
- orig (type: Variant/String)
- trans (type: Variant/String)
...
- Item 1 (type: Variant/Object/JScriptTypeInfo)
- orig (type: Variant/String)
- trans (type: Variant/String)
...
- server_time
- src
Run Code Online (Sandbox Code Playgroud)
arr.src运作良好,但我怎么能得到arr.sentences(0).trans?首先,VBA替换sentences用Sentences,其次(当我试图手动更改JSON)它仍然不允许使用sentenses(0) …