我有一个像下面这样的json:
{"sentences":[{"trans":"something ru","orig":"english word","translit":"Angliyskoye slovo","src_translit":""}], "src":"en","server_time":69}
并解析它:
Function jsonDecode(jsonString As Variant)
Set sc = CreateObject("ScriptControl"): sc.Language = "JScript"
Set jsonDecode = sc.Eval("(" + jsonString + ")")
End Function
Set arr = jsonDecode(txt)
结果arr
包含如下所示的值(在手表中检查):
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
arr.src
运作良好,但我怎样才能获得arr.sentences(0).trans
?首先,VBA将sentences
替换为Sentences
,其次(当我尝试手动更改json时),它仍然不允许使用sentenses(0)
。
答案 0 :(得分:13)
我发现此脚本示例很有用(来自http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075):
Sub getData()
Dim Movie As Object
Dim scriptControl As Object
Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
scriptControl.Language = "JScript"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
.send
Set Movie = scriptControl.Eval("(" + .responsetext + ")")
.abort
With Sheets(2)
.Cells(1, 1).Value = Movie.Title
.Cells(1, 2).Value = Movie.Year
.Cells(1, 3).Value = Movie.Rated
.Cells(1, 4).Value = Movie.Released
.Cells(1, 5).Value = Movie.Runtime
.Cells(1, 6).Value = Movie.Director
.Cells(1, 7).Value = Movie.Writer
.Cells(1, 8).Value = Movie.Actors
.Cells(1, 9).Value = Movie.Plot
.Cells(1, 10).Value = Movie.Language
.Cells(1, 11).Value = Movie.Country
.Cells(1, 12).Value = Movie.imdbRating
End With
End With
End Sub
答案 1 :(得分:1)
这里有两个问题。第一种是访问由JSON解析返回的数组中的字段,第二种是将集合/字段(如句子)重命名为远离VBA保留名称。
让我们首先解决第二个问题。您走在正确的轨道上。首先,将sentences
的所有实例替换为jsentences
,如果JSON中的文本也包含单词一词,则找出一种使替换唯一的方法,例如使用"sentences":[
作为搜索串。您可以使用VBA Replace
方法执行此操作。
完成后,VBA将停止将句子重命名为句子,这就像访问数组一样:
'first, declare the variables you need:
Dim jsent as Variant
'Get arr all setup, then
For Each jsent in arr.jsentences
MsgBox(jsent.orig)
Next
答案 2 :(得分:0)
让我简单一点,但我只是声明了一个Variant,然后将我的REST GET中的响应文本从每个项目之间的引号逗号引号中分离出来,然后通过使用InStrRev查找最后一个引号来获得所需的值。我确信这不像其他建议那么优雅,但对我有用。
varLines = Split(.responsetext, """,""")
strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)