json - 如何设置一个变量等于另一个变量excel vba中的json值
问题描述
我正在解析的 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
推荐阅读
- r - 如何使用 R 中的 st_read 为 WFS 服务请求启用响应分页
- android - 在按下时更改 Android ImagePadding 上的填充
- python-3.x - 将数组写入csv python
- google-cloud-platform - 在 GKE 中为 nginx-ingress 配置 RStudio Server 服务
- laravel - 我可以将 oauth client_secret 存储在服务器上而不是从前端客户端发送它以便每个人都可以看到它吗?
- c++ - 删除或释放
- python - Python pandas 交叉表顺序
- google-api - Google Language API 如何将文本拆分为句子以分配情感?
- azure-devops - 如何弃用/删除旧的 Azure Devops 任务
- sql-server - 调用 CLR 函数“Revisited”时出现 SecurityException 错误