json - 如何设置一个变量等于另一个变量excel vba中的json值

标签 json excel vba parsing

我正在解析的 json 位于此 URL https://reqres.in/api/users?page=2 .我正在使用以下代码来解析它。

Option Explicit

Sub Test_LateBinding()

Dim objRequest As Object
Dim strUrl As String
Dim blnAsync As Boolean
Dim strResponse As String

Set objRequest = CreateObject("MSXML2.XMLHTTP")
strUrl = "https://reqres.in/api/users?page=2"
blnAsync = True

With objRequest
    .Open "GET", strUrl, blnAsync
    .SetRequestHeader "Content-Type", "application/json"
    .Send
    'spin wheels whilst waiting for response
    While objRequest.readyState <> 4
        DoEvents
    Wend
    strResponse = .ResponseText
End With

Debug.Print strResponse

End Sub

我可以成功地将 json 放入 strResponse 变量中。但是假设我想要一个等于“Eve”的变量,它在 json 字符串中的名字下。如何从该 json 字符串中设置变量 firstName = "Eve"。

最佳答案

如果您需要在 VBA 中使用 JSON,那么我建议您使用这个库:

https://github.com/VBA-tools/VBA-JSON

使用该库的简单示例:

Public Sub Tester()

    Dim http As Object, JSON As Object, d
    Set http = CreateObject("MSXML2.XMLHTTP")

    http.Open "GET", "https://reqres.in/api/users?page=2", False
    http.SetRequestHeader "Content-Type", "application/json"
    http.Send
    Set JSON = ParseJson(http.responseText)

    For Each d In JSON("data")
        Debug.Print d("id"), d("first_name")
    Next

End Sub

关于json - 如何设置一个变量等于另一个变量excel vba中的json值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52414592/

相关文章:

c# - 检查Excel文件是否有 "Sheet protection"或 "Custom defined properties in cells"

json - 通过身份引用对象的标准方式(例如,循环引用)?

excel - 我可以在不打开 Excel 或 Word 等相关文件的情况下复制 VBA 代码吗?

javascript - 如何使用 JSON Schema 验证表单?

excel - 使用数字证书自动启用宏?

excel - 在哪里可以找到用于 Internet Explorer 的 VBA 函数

ms-access - 烦人的 vba 命名行为

vba - 使用 Collection.Add 用自定义对象填充 VBA 集合

jquery - 如何捕获json格式的特定元素

python - 无法将转储的 JSON 文件读回 Python