24

我有一个如下的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包含如下值(在 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

arr.src效果很好,但我怎么能得到arr.sentences(0).trans?首先,VBA 替换sentencesSentences,其次(当我尝试手动更改 json 时)它仍然不允许使用sentenses(0).

4

3 回答 3

20

我发现这个脚本示例很有用(来自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
于 2016-12-05T21:39:27.073 回答
4

称我为简单,但我只是声明了一个 Variant 并将响应文本从我的 REST GET 拆分到每个项目之间的引号逗号引号上,然后通过使用 InStrRev 查找最后一个引号来获得我想要的值。我确信这不像其他一些建议那样优雅,但它对我有用。

         varLines = Split(.responsetext, """,""")
        strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)
于 2019-07-05T18:26:55.717 回答
1

这里有两个问题。第一个是访问 JSON 解析返回的数组中的字段,第二个是从 VBA 保留名称中重命名集合/字段(如句子)。

让我们首先解决第二个问题。你走在正确的轨道上。sentences首先,如果您的 JSON 中的文本还包含单词句子,则替换所有实例jsentences,然后找出一种使替换唯一的方法,例如用作"sentences":[搜索字符串。您可以使用 VBAReplace方法来执行此操作。

完成后,VBA 将停止将句子重命名为 Sentences,只需像这样访问数组即可:

'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
于 2020-10-19T14:27:07.393 回答