我知道类似的问题已经被问过并回答过几次了: Parsing JSON in Excel VBA , Excel VBA: Parsed JSON Object Loop
但是,如果我试图访问返回对象中的数组,上述解决方案将不起作用。我从 Google Translate API 接收到以下格式的 JSON 对象:
"{
"sentences":[
{
"trans":"Responsibility\n",
"orig":"??",
"translit":"",
"src_translit":"Zérèn"
},
{
"trans":"Department",
"orig":"??",
"translit":"",
"src_translit":"Bùmén"
}
],
"src":"zh-CN",
"server_time":86
}”
我希望能够访问两个翻译后的句子作为句子(0)和句子(1)。我可以使用之前帖子中的 GetProperty() 方法来检索句子对象,但我无法访问其成员,因为它是 JScriptTypeInfo 类型的对象,而不是数组。
我尝试使用类似于此处描述的方法将句子对象转换为 JScript 中的数组:How to pass arrays between javaScript and VBA .出于某种原因,我只能让它返回数组的第一个值。
执行此操作的最佳方法是什么?
最佳答案
您可以使用 ScriptControl
对象来创建可以运行 javascript 的环境。如果您习惯于在网页中使用 JSON,那么这可能是一种简单的方法。
例子:
Sub Tester()
Dim json As String
Dim sc As Object
Dim o
Set sc = CreateObject("scriptcontrol")
sc.Language = "JScript"
json = {get your json here}
sc.Eval "var obj=(" & json & ")" 'evaluate the json response
'add some accessor functions
sc.AddCode "function getSentenceCount(){return obj.sentences.length;}"
sc.AddCode "function getSentence(i){return obj.sentences[i];}"
Debug.Print sc.Run("getSentenceCount")
Set o = sc.Run("getSentence", 0)
Debug.Print o.trans, o.orig
End Sub
如何使用脚本控件调用函数:http://support.microsoft.com/kb/184740
使用脚本控件:https://msdn.microsoft.com/en-us/library/aa227633(v=vs.60).aspx
关于javascript - 在 Excel VBA 中解析 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14822672/