在Excel VBA代码中处理XMLHttp响应中的JSON对象 [英] Handle JSON Object in XMLHttp response in Excel VBA Code
问题描述
我需要处理JSON对象,这是Excel VBA中XMLHTTPRequest的响应。我写下面的代码,但没有成功。请指导我
I am need of handling JSON Object which is the response of XMLHTTPRequest in Excel VBA. I wrote below code but not succeeded. Please guide me.
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 + "')")
我收到错误运行时错误'429'ActiveX组件无法在行<$ c中创建对象 $ c> Set sc = CreateObject(ScriptControl)
I am getting the error Run-time error '429' ActiveX component can't create object in the line Set sc = CreateObject("ScriptControl")
而且,一旦我们解析了JOSN对象,如何访问JSON的值对象?
And, Once we parsed the JOSN Object, how to access the values of JSON Object?
PS我的JSON对象示例: {成功:true,消息:Blah blah}
P.S. My JSON Object sample: {"Success":true,"Message":"Blah blah"}
推荐答案
该代码获取nseindia站点中的数据,该数据作为 responseDiv
元素中的JSON字符串。
The code gets the data from nseindia site which comes as a JSON string in responseDiv
element.
必需参考
3类模块我已经使用
- cJSONScript
- cStringBuilder
- JSON
(我从 here )
您可以从这个链接
标准模块
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
这篇关于在Excel VBA代码中处理XMLHttp响应中的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!