I used to use the following VBA code to parse data.
However, now the JSON parser is giving the following error.
I use the following VBA code.
Option Explicit
Sub nse()
Dim req As New MSXML2.XMLHTTP60
Dim url As String, defaultPayload As String, requestPayload As String, results() As String
Dim payloadJSON As Object, responseJSON As Object, item As Object
Dim startD As Date, endD As Date
Dim key As Variant
Dim i As Long, j As Long
Dim rng As Range
startD = "01/02/2020" 'Start date
endD = "29/02/2020" 'end date
url = "https://www.niftyindices.com/Backpage.aspx/getHistoricaldatatabletoString"
defaultPayload = "{'name':'NIFTY 50','startDate':'','endDate':''}"
Set rng = ThisWorkbook.Worksheets("NSE").Range("A2") 'Output worksheet name.
Set payloadJSON = JsonConverter.ParseJson(defaultPayload)
payloadJSON("startDate") = Day(startD) & "-" & MonthName(Month(startD), True) & "-" & Year(startD) '01-Feb-2020
payloadJSON("endDate") = Day(endD) & "-" & MonthName(Month(endD), True) & "-" & Year(endD) '29-Feb-2020
requestPayload = JsonConverter.ConvertToJson(payloadJSON)
With req
.Open "POST", url, False
.setRequestHeader "Content-Type", "application/json; charset=UTF-8"
.setRequestHeader "X-Requested-With", "XMLHttpRequest"
.send requestPayload
Set responseJSON = JsonConverter.ParseJson(.responseText)
End With
Debug.Print responseJSON("d")
Set responseJSON = JsonConverter.ParseJson(responseJSON("d"))
ReDim results(1 To responseJSON.Count, 1 To 7)
i = 0
For Each item In responseJSON
i = i + 1
j = 0
For Each key In item
j = j + 1
results(i, j) = item(key)
Next key
Next item
rng.Resize(UBound(results, 1), UBound(results, 2)) = results
End Sub
I understand the the Error is in Json Parser.
I am not able to decode the error.
Thanks in Advance…
2
Answers
You’re not properly constructing the payload for the POST. It should look like this:
Note that the value for the key
cinfo
is itself a JSON string (not a nested JSON object!) so it needs the proper escaping…Revised and working for me:
An alternative similar to Tim Williams’ answer is;