How to retrieve JSON response using VBA? - json

I make a request to a website and paste the JSON response into a single cell.
I get an object required 424 error.
Sub GetJSON()
Dim hReq As Object
Dim JSON As Dictionary
Dim var As Variant
Dim ws As Worksheet
Set ws = Title
'create our URL string and pass the user entered information to it
Dim strUrl As String
strUrl = Range("M24").Value
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.Send
End With
'wrap the response in a JSON root tag "data" to count returned objects
Dim response As String
response = "{""data"":" & hReq.responseText & "}"
Set JSON = JsonConverter.ParseJson(response)
'set array size to accept all returned objects
ReDim var(JSON("data").Count, 1)
Cells(25, 13) = JSON
Erase var
Set var = Nothing
Set hReq = Nothing
Set JSON = Nothing
End Sub
The URL that gives me the response in cell "M24":
https://earthquake.usgs.gov/ws/designmaps/asce7-10.json?latitude=36.497452&longitude=-86.949479&riskCategory=III&siteClass=C&title=Seismic
The code after Qharr's response. I get a run time 0 error even though the error says it ran successfully. Nothing is copied to my cells.
Public Sub GetInfo()
Dim URL As String, json As Object
Dim dict As Object
URL = "https://earthquake.usgs.gov/ws/designmaps/asce7-10.json?latitude=36.497452&longitude=-86.949479&riskCategory=III&siteClass=C&title=Seismic"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", URL, False
.Send
Set json = JsonConverter.ParseJson(.responseText) '<== dictionary
ThisWorkbook.Worksheets("Title").Cells(1, 1) = .responseText
Set dict = json("response")("data")
ws.Cells(13, 27) = "ss: " & dict("ss") & Chr$(10) & "s1: " & dict("s1")
End With
End Sub

I'm not clear what you mean. The entire response can go in a cell as follows.
JSON is an object so you would need Set keyword but you can't set a cell range to the dictionary object - the source of your error.
Option Explicit
Public Sub GetInfo()
Dim URL As String, json As Object
URL = "https://earthquake.usgs.gov/ws/designmaps/asce7-10.json?latitude=36.497452&longitude=-86.949479&riskCategory=III&siteClass=C&title=Seismic"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", URL, False
.send
Set json = JsonConverter.ParseJson(.responseText) '<== dictionary
ThisWorkbook.Worksheets("Sheet1").Cells(1, 1) = .responseText
End With
End Sub
When you use parsejson you are converting to a dictionary object which you need to do something with. There is simply too much data nested inside to write anything readable (if limit not exceeded) into one cell.
Inner dictionary data quickly descends into nested collections. The nested collection count comes from
Dim dict As Object
Set dict = json("response")("data")
Debug.Print "nested collection count = " & dict("sdSpectrum").Count + dict("smSpectrum").Count
To get just s1 and ss values parse them out:
Dim dict As Object
Set dict = json("response")("data")
ws.Cells(1, 2) = "ss: " & dict("ss") & Chr$(10) & "s1: " & dict("s1")

I have figured out the solution to pasting the response text with Excel 2003. Below is my finished code.
Public Sub datagrab()
Dim URL As String
Dim ws As Object
Dim xmlhttp As New MSXML2.XMLHTTP60
URL = Range("M24").Value 'This is the URL I'm requesting from
xmlhttp.Open "GET", URL, False
xmlhttp.Send
Worksheets("Title").Range("M25").Value = xmlhttp.responseText
End Sub

Related

How to parse highlighted part in Image with Json

I am trying this cod but ist showing type mismatch.
Option Explicit
Sub nse5()
Dim req As New MSXML2.XMLHTTP60
Dim url As String
Dim json As Object
url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
With req
.Open "GET", url, False
.send
Set json = JsonConverter.ParseJson(.responseText)
End With
Debug.Print json("filtered")("data")(1)(2)("openInterest")
End Sub
I have tryed many ways but i am suffring from it that hou to bring specific data to print

How to extract data from an API JSON response?

I am trying to extract data from an API JSON response. Everywhere I read says to use JsonConverter.ParseJson and then you can use the data by doing something like Debug.Print jsonObject("name").
I get a 424 error.
Sub get_request_expansions()
Dim ws As Worksheet
Dim jsonObject As Object
Dim sURL As String
Set request = CreateObject("winhttp.winhttprequest.5.1")
sURL = "https://api.scryfall.com/sets/jmp/"
request.Open "GET", sURL, False
request.send
'----------
Debug.Print request.responseText
Set jsonObject = JsonConverter.ParseJson(request.responseText)
Debug.Print jsonObject("name")
'----------
request.abort
End Sub

Why can't I assign to a variable a JSON value that I can see in Debug mode?

I’ve run into an issue retrieving values from a non-itemized JSON object. I thought it was simple do so … Just reference the object with the field you want (e.g. JSON(“title”). But I cannot retrieve a value even though it IS there.
This code demonstrates what I’m talking about. (Be sure to put a breakpoint on the “next” line, or it will run for a while.) The strID and strTitle values are not assigned and do not print out. But if you go to the immediate window and type
? JSON2("ID")
? JOON2(“title”)
You get the values. What am I doing wrong? Why can’t I get these values into variables?
Sub testMovie2()
Dim Url As String, data As String, data2 As String
Dim xml As Object, JSON As Object, JSON2 As Object, colObj As Object, colobj2 As Object, item, item2
Dim strID As String, strTitle As String
Url = "https://www.tiff.net/data/films-events-2018.json"
data = getHTTP(Url)
Set JSON = JsonConverter.ParseJson(data)
Set colObj = JSON("items")
For Each item In colObj
Url = "https://www.tiff.net/data/films/" & item("id") & ".JSON"
data2 = getHTTP(Url)
Set JSON2 = JsonConverter.ParseJson(data2)
strID = JSON2("ID")
Debug.Print strID
strTitle = JSON2("Title")
Debug.Print strTitle
Next
End Sub
JSON2 is a dictonary object and to retrieve element from dictonary use below
with key
JSON2.item("id")
JSON2.item("title")
OR
with index
JSON2.Items()(4)
JSON2.Items()(5)
By default dictionary objects are case sensitive
So JSON2("ID") not equals to JSON2("id")
To make it case insensitive use:
JSON2.CompareMode = vbTextCompare
Code:
Sub testMovie2()
Dim url As String, data As String, data2 As String
Dim xml As Object, JSON As Object, JSON2 As Object, colObj As Object, colobj2 As Object, item, item2
Dim strID As String, strTitle As String
url = "https://www.tiff.net/data/films-events-2018.json"
data = getHTTP(url)
Set JSON = JsonConverter.ParseJson(data)
Set colObj = JSON("items")
For Each item In colObj
url = "https://www.tiff.net/data/films/" & item("id") & ".JSON"
data2 = getHTTP(url)
Set JSON2 = JsonConverter.ParseJson(data2)
strID = JSON2.item("id")
Debug.Print strID
strTitle = JSON2.item("title")
Debug.Print strTitle
Next
End Sub
Function getHTTP(url) As String
Dim data As String
Dim xml As Object
Set xml = CreateObject("MSXML2.ServerXMLHTTP")
With xml
.Open "GET", url, False
.setRequestHeader "Content-Type", "text/json"
.send
data = .responseText
End With
getHTTP = data
End Function

VBA access to a json property without name property

I'm trying to access in VBA to over 508 "tank_id"s from a JSON file as you can see here.
I'm using cStringBuilder, cJSONScript and JSONConverter to parse the JSON file.
My main issue is that I can't pass threw all those ids because I don't know how to get the "1" "33" "49" "81" that are without names.
Here si the code I tried to get them, without success.
Const myurl2 As String = "https://api.worldoftanks.eu/wot/encyclopedia/vehicles/?application_id=demo&fields=tank_id"
Sub List_id_vehicules()
Dim strRequest
Dim xmlHttp: Set xmlHttp = CreateObject("msxml2.xmlhttp")
Dim response As Object
Dim rows As Integer
Dim counter As Integer
Dim j As String
Dim k As Integer: k = 2
Dim url As String
url = myurl2
xmlHttp.Open "GET", url, False
xmlHttp.setRequestHeader "Content-Type", "text/xml"
xmlHttp.send
While Not xmlHttp.Status = 200 '<---------- wait
Wend
Set response = ParseJson(xmlHttp.ResponseText)
rows = response("meta")("count")
For counter = 1 To rows
j = counter
Dim yop As String
yop = "data[" & j & "][" & j & "]"
Sheets(2).Cells(1 + counter, 1).Value = response('data[counter]')['tank_id']
Next counter
END Sub
Could someone help me ?
The JSONConverter essentially parses the JSON text string into a set of nested Dictionary objects. So when the ParseJson function returns an Object, it's really a Dictionary. Then, when you access response("meta"), the "meta" part is the Key to the Dictionary object. It's the same thing as you nest down through the JSON.
So when you try to access response("data")("3137"), you're accessing the Dictionary returned by response("data") with the key="3137". Now the trick becomes how to get all the Keys from the response("data") object.
Here's a sample bit of code to illustrate how you can list all the tank IDs in the JSON data section:
Option Explicit
Sub ListVehicleIDs()
Const jsonFilename As String = "C:\Temp\tanks.json"
Dim fileHandle As Integer
Dim jsonString As String
fileHandle = FreeFile
Open jsonFilename For Input As #fileHandle
jsonString = Input$(LOF(fileHandle), #fileHandle)
Close #fileHandle
Dim jsonObj As Object
Set jsonObj = ParseJson(jsonString)
Dim tankCount As Long
tankCount = jsonObj("meta")("count")
Dim tankIDs As Dictionary
Set tankIDs = jsonObj("data")
Dim tankID As Variant
For Each tankID In tankIDs.keys
Debug.Print "Tank ID = " & tankID
Next tankID
End Sub

How to decode JSON in a .VBS Script

I'm trying to receive JSON through a get request over MSXML2.ServerXMLHTTP and then to parse that into a VBS dictionary.
I'm able to receive the response in what looks like the proper JSON format. However I am met with an error When I use this VbsJson class's decode method on the responseText of my request.
Cannot convert variant type of (Dispatch) to Olestr
I'm an absolute newcomer to vbs and would like a simple way to get this data into a dictionary (better if I can also define the fields that I want to extract).
The code:
Sub Search(Sender)
Dim Resp, Data
Dim UrlToGet2
UrlToGet2 = http://www.mywebsite.com/json
Set Data = CreateObject("Scripting.Dictionary")
Dim xHttp: Set xHttp = createobject("MSXML2.ServerXMLHTTP")
xHttp.Open "GET", UrlToGet2, False
xHttp.setRequestHeader "Content-Type", "application/json"
xHttp.Send
If xHttp.Status <> 200 Then
Set Resp = CreateObject("Scripting.Dictionary")
Resp.Add "success", "false"
Resp.Add "error", "HTTP Error: " & xHttp.Status & " " & xHttp.StatusText
Exit Sub
End If
Set Resp = CreateObject("Scripting.Dictionary")
Dim x, json
Set json = New VbsJson
Set x = json.Decode(xHttp.responseText)
With Resp
Dim a: a = x.Keys
Dim i
For i = 0 To x.Count -1
.Add a(i), x(a(i))
Next
End With
Set xHttp = Nothing
End Sub