gpt4 book ai didi

json - 在 Excel VBA 代码中处理 XMLHttp 响应中的 JSON 对象

转载 作者:行者123 更新时间:2023-12-01 17:38:01 28 4
gpt4 key购买 nike

我需要处理一个 JSON 对象,它是 Excel VBA 中 XMLHTTPRequest 的响应。我写了下面的代码,但它不起作用:

  Dim sc As Object
Set sc = CreateObject("ScriptControl")
sc.Language = "JScript"

Dim strURL As String: strURL = "blah blah"

Dim strRequest
Dim XMLhttp: Set XMLhttp = CreateObject("msxml2.xmlhttp")
Dim response As String

XMLhttp.Open "POST", strURL, False
XMLhttp.setrequestheader "Content-Type", "application/x-www-form-urlencoded"
XMLhttp.send strRequest
response = XMLhttp.responseText
sc.Eval ("JSON.parse('" + response + "')")

我在 Set sc = CreateObject("ScriptControl") 行中收到错误运行时错误“429”ActiveX 组件无法创建对象

解析 JSON 对象后,如何访问 JSON 对象的值?

附注我的 JSON 对象示例:{"Success":true,"Message":"Blah blah"}

最佳答案

代码从 nseindia 站点获取数据,该数据以 JSON 字符串形式存在于 responseDiv 元素中。

所需引用文献

enter image description here

我用过的3类模块

  • cJSONScript
  • cStringBuilder
  • JSON

(我从 here 中选择了这些类模块)

您可以从此link下载该文件

标准模块

Const URl As String = "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=ICICIBANK"
Sub xmlHttp()

Dim xmlHttp As Object
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlHttp.Open "GET", URl & "&rnd=" & WorksheetFunction.RandBetween(1, 99), False
xmlHttp.setRequestHeader "Content-Type", "text/xml"
xmlHttp.send

Dim html As MSHTML.HTMLDocument
Set html = New MSHTML.HTMLDocument
html.body.innerHTML = xmlHttp.ResponseText

Dim divData As Object
Set divData = html.getElementById("responseDiv")
'?divData.innerHTML
' Here you will get a string which is a JSON data

Dim strDiv As String, startVal As Long, endVal As Long
strDiv = divData.innerHTML
startVal = InStr(1, strDiv, "data", vbTextCompare)
endVal = InStr(startVal, strDiv, "]", vbTextCompare)
strDiv = "{" & Mid(strDiv, startVal - 1, (endVal - startVal) + 2) & "}"


Dim JSON As New JSON

Dim p As Object
Set p = JSON.parse(strDiv)

i = 1
For Each item In p("data")(1)
Cells(i, 1) = item
Cells(i, 2) = p("data")(1)(item)
i = i + 1
Next

End Sub

关于json - 在 Excel VBA 代码中处理 XMLHttp 响应中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16817545/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com