为什么我不能为变量分配在调试模式下可以看到的JSON值?

时间:2018-08-11 18:15:55

标签: json ms-access

我遇到了一个问题,即从非项目化的JSON对象检索值。我认为这样做很简单……只需使用所需字段(例如JSON(“ title”))引用对象即可。但是即使有值,我也无法检索。

此代码演示了我在说什么。 (请确保在“下一条”行上放置一个断点,否则它将运行一会儿。)未分配strID和strTitle值,也不会打印出来。但是,如果您进入立即窗口并输入

? JSON2(“ ID”) ? JOON2(“标题”)

您将获得值。我究竟做错了什么?为什么不能将这些值转换为变量?

Sub testMovie2()

Dim Url As String, data As String, data2 As String
Dim xml As Object, JSON As Object, JSON2 As Object, colObj As Object, colobj2 As Object, item, item2
Dim strID As String, strTitle As String

Url = "https://www.tiff.net/data/films-events-2018.json"
data = getHTTP(Url)
Set JSON = JsonConverter.ParseJson(data)
Set colObj = JSON("items")
For Each item In colObj
    Url = "https://www.tiff.net/data/films/" & item("id") & ".JSON"
    data2 = getHTTP(Url)
    Set JSON2 = JsonConverter.ParseJson(data2)
    strID = JSON2("ID")
    Debug.Print strID
    strTitle = JSON2("Title")
    Debug.Print strTitle
Next
End Sub

1 个答案:

答案 0 :(得分:1)

JSON2是字典对象,并从下面的字典使用中检索元素

带键

JSON2.item("id")
JSON2.item("title")

OR

具有索引

JSON2.Items()(4)
JSON2.Items()(5)


默认情况下,字典对象区分大小写

所以JSON2("ID")不等于JSON2("id")

要使其不区分大小写,请使用:

JSON2.CompareMode = vbTextCompare


代码:

Sub testMovie2()

    Dim url As String, data As String, data2 As String
    Dim xml As Object, JSON As Object, JSON2 As Object, colObj As Object, colobj2 As Object, item, item2
    Dim strID As String, strTitle As String

    url = "https://www.tiff.net/data/films-events-2018.json"
    data = getHTTP(url)
    Set JSON = JsonConverter.ParseJson(data)
    Set colObj = JSON("items")
    For Each item In colObj
        url = "https://www.tiff.net/data/films/" & item("id") & ".JSON"
        data2 = getHTTP(url)

        Set JSON2 = JsonConverter.ParseJson(data2)
        strID = JSON2.item("id")
        Debug.Print strID

        strTitle = JSON2.item("title")
        Debug.Print strTitle

    Next
End Sub
Function getHTTP(url) As String

    Dim data As String
    Dim xml As Object

    Set xml = CreateObject("MSXML2.ServerXMLHTTP")
    With xml
        .Open "GET", url, False
        .setRequestHeader "Content-Type", "text/json"
        .send
        data = .responseText
    End With

    getHTTP = data

End Function

enter image description here