Extracting JSON properties using JSON Parser - Coin Market Cap API - json

I am using the JsonConverter.bas module to parse the json received from my call (see below)
{
"status": {
"timestamp": "2020-06-01T07:43:13.192Z",
"error_code": 0,
"error_message": null,
"elapsed": 15,
"credit_count": 1,
"notice": null
},
"data": {
"ETH": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"slug": "ethereum",
"num_market_pairs": 5250,
"date_added": "2015-08-07T00:00:00.000Z",
"tags": ["mineable"],
"max_supply": null,
"circulating_supply": 111165464.9365,
"total_supply": 111165464.9365,
"is_active": 1,
"platform": null,
"cmc_rank": 2,
"is_fiat": 0,
"last_updated": "2020-06-01T07:41:24.000Z",
"quote": {
"GBP": {
"price": 192.38035284151908,
"volume_24h": 10939279331.24139,
"percent_change_1h": -0.0312479,
"percent_change_24h": 0.19816661,
"percent_change_7d": 15.48893301,
"market_cap": 21386051368.275387,
"last_updated": "2020-06-01T07:41:01.000Z"
}
}
}
}
}
But when I attempt to get a property, let's say "id". I get a
runtime error '424' - Object required.
I have tried:
initializing my JsonConverter instance as an Object/Variant/Dictionary
initializing my att iterative variable for looping as an Object/Variant/Dictionary.
In the code below both JSON and att variables are declared as Objects:
Sub TestApi()
Dim JSON As Object
Dim api_key As String
Dim explorer As MSXML2.XMLHTTP60
Dim endpoint As String
api_key = "********-****-****-****-************"
endpoint = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=ETH&convert=GBP"
Set explorer = New MSXML2.XMLHTTP60
explorer.Open "GET", endpoint, False
explorer.SetRequestHeader "Accept", "application/json"
explorer.SetRequestHeader "X-CMC_PRO_API_KEY", api_key
explorer.Send
Debug.Print explorer.responseText
Set JSON = JsonConverter.ParseJson(explorer.responseText)
Dim att As Object
For Each att In JSON("data")
Debug.Print att("id")
Next att
End Sub
Ideally I'd like to pick a list of properties and have them printed or used in various functions.
Is there something that I am missing?

Related

Json VBA Parse - Run time error 424 - Object required

I am trying to extract value for regularMarketPreviousClose from the Yahoo API json reponse.
I get a Run time error 424 - Object required, in the line - Set price = reply("result").
Can someone figure out what's wrong in this code. I have provided both my code and the json data I get from Yahoo API.
Here is the json response text I get from yahoo API
{
"quoteResponse": {
"result": [
{
"language": "en-US",
"region": "US",
"quoteType": "EQUITY",
"typeDisp": "Equity",
"quoteSourceName": "Delayed Quote",
"triggerable": false,
"customPriceAlertConfidence": "LOW",
"currency": "USD",
"tradeable": false,
"exchange": "PNK",
"shortName": "Tandy Leather Factory, Inc.",
"longName": "Tandy Leather Factory, Inc.",
"messageBoardId": "finmb_30741",
"exchangeTimezoneName": "America/New_York",
"exchangeTimezoneShortName": "EDT",
"gmtOffSetMilliseconds": -14400000,
"market": "us_market",
"esgPopulated": false,
"marketState": "REGULAR",
"fullExchangeName": "Other OTC",
"financialCurrency": "USD",
"regularMarketOpen": 4.95,
"averageDailyVolume3Month": 9237,
"averageDailyVolume10Day": 22020,
"fiftyTwoWeekLowChange": 1.2399998,
"fiftyTwoWeekLowChangePercent": 0.33423173,
"fiftyTwoWeekRange": "3.71 - 5.3",
"fiftyTwoWeekHighChange": -0.35000038,
"fiftyTwoWeekHighChangePercent": -0.066037804,
"fiftyTwoWeekLow": 3.71,
"fiftyTwoWeekHigh": 5.3,
"dividendDate": 1407456000,
"earningsTimestamp": 1639991127,
"earningsTimestampStart": 1648065600,
"earningsTimestampEnd": 1648238400,
"trailingAnnualDividendRate": 0,
"trailingPE": 50.510204,
"trailingAnnualDividendYield": 0,
"epsTrailingTwelveMonths": 0.098,
"epsForward": 0.43,
"epsCurrentYear": 0.26,
"priceEpsCurrentYear": 19.038462,
"sharesOutstanding": 8543230,
"bookValue": 6.038,
"fiftyDayAverage": 4.9554,
"fiftyDayAverageChange": -0.005400181,
"fiftyDayAverageChangePercent": -0.0010897568,
"twoHundredDayAverage": 4.89935,
"twoHundredDayAverageChange": 0.050649643,
"twoHundredDayAverageChangePercent": 0.010338033,
"marketCap": 42288988,
"forwardPE": 11.511627,
"priceToBook": 0.8198078,
"sourceInterval": 15,
"exchangeDataDelayedBy": 0,
"averageAnalystRating": "2.0 - Buy",
"firstTradeDateMilliseconds": 749136600000,
"priceHint": 4,
"regularMarketChange": -0.05000019,
"regularMarketChangePercent": -1.0000038,
"regularMarketTime": 1648141256,
"regularMarketPrice": 4.95,
"regularMarketDayHigh": 4.95,
"regularMarketDayRange": "4.95 - 4.95",
"regularMarketDayLow": 4.95,
"regularMarketVolume": 604,
"regularMarketPreviousClose": 5,
"displayName": "Tandy Leather Factory",
"symbol": "TLFA"
},
{
"language": "en-US",
"region": "US",
"quoteType": "EQUITY",
"typeDisp": "Equity",
"quoteSourceName": "Nasdaq Real Time Price",
"triggerable": true,
"customPriceAlertConfidence": "HIGH",
"currency": "USD",
"tradeable": false,
"exchange": "NCM",
"shortName": "ChromaDex Corporation",
"longName": "ChromaDex Corporation",
"messageBoardId": "finmb_5034211",
"exchangeTimezoneName": "America/New_York",
"exchangeTimezoneShortName": "EDT",
"gmtOffSetMilliseconds": -14400000,
"market": "us_market",
"esgPopulated": false,
"marketState": "REGULAR",
"fullExchangeName": "NasdaqCM",
"financialCurrency": "USD",
"regularMarketOpen": 2.52,
"averageDailyVolume3Month": 421352,
"averageDailyVolume10Day": 520790,
"fiftyTwoWeekLowChange": 0.5400001,
"fiftyTwoWeekLowChangePercent": 0.2797928,
"fiftyTwoWeekRange": "1.93 - 11.2",
"fiftyTwoWeekHighChange": -8.73,
"fiftyTwoWeekHighChangePercent": -0.77946424,
"fiftyTwoWeekLow": 1.93,
"fiftyTwoWeekHigh": 11.2,
"earningsTimestamp": 1646841720,
"earningsTimestampStart": 1651694400,
"earningsTimestampEnd": 1652126400,
"trailingAnnualDividendRate": 0,
"trailingAnnualDividendYield": 0,
"epsTrailingTwelveMonths": -0.404,
"epsForward": -0.15,
"epsCurrentYear": -0.29,
"priceEpsCurrentYear": -8.5172415,
"sharesOutstanding": 68126000,
"bookValue": 0.464,
"fiftyDayAverage": 2.664,
"fiftyDayAverageChange": -0.194,
"fiftyDayAverageChangePercent": -0.072822824,
"twoHundredDayAverage": 5.90605,
"twoHundredDayAverageChange": -3.4360502,
"twoHundredDayAverageChangePercent": -0.5817848,
"marketCap": 168724224,
"forwardPE": -16.466665,
"priceToBook": 5.323276,
"sourceInterval": 15,
"exchangeDataDelayedBy": 0,
"pageViewGrowthWeekly": 0.02642558,
"averageAnalystRating": "1.7 - Buy",
"firstTradeDateMilliseconds": 1214400600000,
"priceHint": 4,
"regularMarketChange": -0.03999996,
"regularMarketChangePercent": -1.5936241,
"regularMarketTime": 1648145420,
"regularMarketPrice": 2.47,
"regularMarketDayHigh": 2.99,
"regularMarketDayRange": "2.45 - 2.99",
"regularMarketDayLow": 2.45,
"regularMarketVolume": 221155,
"regularMarketPreviousClose": 2.51,
"bid": 2.46,
"ask": 2.47,
"bidSize": 9,
"askSize": 10,
"displayName": "ChromaDex",
"symbol": "CDXC"
}
],
"error": null
}
}
Here is my VBA code
Sub RequestURL()
Dim i As Integer
Dim rstring As String
Dim item As Object
Dim lrow As Integer: lrow = Range("A10000").End(xlUp).Row
rstring = "https://yfapi.net/v6/finance/quote?region=US&lang=en&symbols="
For i = 2 To lrow
rstring = rstring & Tsheet.Range("A" & i).Value & "%2C"
Next i
rstring = Left(rstring, Len(rstring) - 3)
Dim request As New WinHttpRequest
Dim key As String
key = "mykey"
request.Open "get", rstring
request.SetRequestHeader "X-API-Key", key
request.Send
If request.Status <> 200 Then
MsgBox request.ResponseText
Else
MsgBox request.ResponseText
End If
' To access Data
Dim reply As Object
Set reply = JsonConverter.ParseJson(request.ResponseText)
Dim price As Collection
Set price = reply("result")
Dim result As Dictionary
For Each result In price
Debug.Print result("regularMarketPreviousClose")
Next
End Sub
JSON uses name value pairs format.
Curly brackets hold objects and square ones hold array.
Result is an object itself and holds array of objects in it.
Since , it is inside quoteResponse. You must address it first and then the result inside it.
Set price = reply("quoteResponse")("result")

VBA: count items in JSON response string / trello get Cards count in a List

I'm using VBA-web (https://vba-tools.github.io/VBA-Web/) to access trello api, to get cards in a list
My function looks like that:
Public Function CountCardsinList(ListId As String) As Integer
WebHelpers.EnableLogging = False
Dim TrelloClient As New WebClient
TrelloClient.BaseUrl = "https://api.trello.com/1/"
Dim Request As New WebRequest
Request.Format = WebFormat.Json
Request.ResponseFormat = Json
Request.Resource = "lists/{ListId}/cards"
Request.AddUrlSegment "ListId", ListId
Request.AddQuerystringParam "key", TrelloAPIKey
Request.AddQuerystringParam "token", TrelloAPIToken
Request.AddQuerystringParam "filter", "open"
Dim Response As WebResponse
Set Response = TrelloClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Debug.Print Response.Content '
'Response.Data("idList").Count
Debug.Print "CountCardsinList =>>> " & Response.Content
CountCardsinList = Response.Data("idList").Count
Else
MsgBox Response.StatusDescription, vbCritical, "Error " & Response.StatusCode
CountCardsinList = ""
End If
Debug.Print "CountCardsinList =>>> " & Response.Content
'Set CountCardsinList = Request
End Function
I receive correct JSON reply from the api:
[{
"id": "584e798dd570ae187b293e5b",
"checkItemStates": null,
"closed": false,
"dateLastActivity": "2016-12-30T09:24:57.531Z",
"desc": "",
"descData": null,
"idBoard": "57873ba94794058756fa0a96",
"idList": "57873bb3a725f734089702b2",
"idMembersVoted": [],
"idShort": 90,
"idAttachmentCover": null,
"manualCoverAttachment": false,
"idLabels": ["57873ba984e677fd3683bef8"],
"name": "card name / other stuff",
"pos": 1999.9923706054688,
"shortLink": "izoqvWJk",
"badges": {
"votes": 0,
"viewingMemberVoted": false,
"subscribed": false,
"fogbugz": "",
"checkItems": 0,
"checkItemsChecked": 0,
"comments": 0,
"attachments": 0,
"description": false,
"due": "2016-12-26T11:00:00.000Z",
"dueComplete": false
},
"dueComplete": false,
"due": "2016-12-26T11:00:00.000Z",
"idChecklists": [],
"idMembers": ["54f0cc079bf18f2798dda8bd"],
"labels": [{
"id": "57873ba984e677fd3683bef8",
"idBoard": "57873ba94794058756fa0a96",
"name": "Urgent",
"color": "red",
"uses": 14
}],
"shortUrl": "https://trello.com/c/vfvfdvdfv",
"subscribed": false,
"url": "https://trello.com/c/fdvfdvdfv/cfvdfv"
},
{
"id": "5832c2fa7f55fe5637d972ea",
"checkItemStates": null,
"closed": false,
"dateLastActivity": "2016-12-30T09:25:09.222Z",
"desc": "",
"descData": null,
"idBoard": "57873ba94794058756fa0a96",
"idList": "57873bb3a725f734089702b2",
"idMembersVoted": [],
"idShort": 80,
"idAttachmentCover": null,
"manualCoverAttachment": false,
"idLabels": ["57873ba984e677fd3683bef6"],
"name": "other card name",
"pos": 2023.9922790527344,
"shortLink": "XhUPgcsD",
"badges": {
"votes": 0,
"viewingMemberVoted": false,
"subscribed": false,
"fogbugz": "",
"checkItems": 0,
"checkItemsChecked": 0,
"comments": 0,
"attachments": 0,
"description": false,
"due": "2016-12-30T15:00:00.000Z",
"dueComplete": false
},
"dueComplete": false,
"due": "2016-12-30T15:00:00.000Z",
"idChecklists": [],
"idMembers": ["54fdbe1a8ecdf184596c7c07"],
"labels": [{
"id": "57873ba984e677fd3683bef6",
"idBoard": "57873ba94794058756fa0a96",
"name": "Medium",
"color": "yellow",
"uses": 1
}],
"shortUrl": "https://trello.com/c/XhdfvdfvUPgcsD",
"subscribed": false,
"url": "https://trello.com/c/XhUPgcsfdvdffvD/
"
But I cannot correctly count idList -> and I'm trying to get number of cards in a list, by using Response.Data("idList").Count
Any information how to do it proper way? or which is the best way to parse JSON data?
General:
Your JSON isn't properly closed. I added }] to the end to close and placed in cell A1 of activesheet (as I don't have the API info). I then read that in from the cell as if it were response text.
Process:
I then used JSONConverter to parse this string from the sheet. This requires you to also add a reference to Microsoft Scripting Runtime via VBE > Tools > References.
The returned object is a collection of dictionaries. I test each dictionary for the existence of an idList key and if present add 1 to the variable itemCount, which keeps track of how many idLists there are.
Code:
Public Sub GetInfoFromSheet()
Dim jsonStr As String, item As Object, json As Object, itemCount As Long
jsonStr = [A1]
Set json = JsonConverter.ParseJson(jsonStr)
For Each item In json 'collection
If item.Exists("idList") Then itemCount = itemCount + 1
Next item
Debug.Print "idList count: " & itemCount
End Sub

Getting values from twitch.tv JSON response

I have just started using JSON.NET and I am having some trouble getting the values from JSON items.
I have come across some code over the past few days which will allow me to grab the names but not he associated values.
I am working with the twitch.tv Web API. Here is my code:
Dim sUrl As String = Convert.ToString("https://api.twitch.tv/kraken/streams/") & sUsername
Dim wRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(sUrl), HttpWebRequest)
wRequest.ContentType = "application/json"
wRequest.Accept = "application/vnd.twitchtv.v3+json"
wRequest.Method = "GET"
Dim wResponse As WebResponse = wRequest.GetResponse()
Dim dataStream As Stream = wResponse.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim res As String = reader.ReadToEnd()
Dim outer As JToken = JToken.Parse(res)
Dim inner As JObject = outer("stream").Value(Of JObject)()
Dim keys As List(Of String) = inner.Properties().[Select](Function(p) p.Name).ToList()
For Each k As String In keys
Debug.WriteLine(k)
Next
reader.Close()
wResponse.Close()
The raw JSON is as follows:
{
"_links": {
"self": "https: //api.twitch.tv/kraken/streams/jojosaysbreee",
"channel": "https: //api.twitch.tv/kraken/channels/jojosaysbreee"
},
"stream": {
"_id": 16717827552,
"game": "TomClancy'sRainbowSix: Siege",
"viewers": 15,
"created_at": "2015-09-30T21: 19: 10Z",
"video_height": 720,
"average_fps": 59.9630366205,
"is_playlist": false,
"_links": {
"self": "https: //api.twitch.tv/kraken/streams/jojosaysbreee"
},
"preview": {
"small": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-80x45.jpg",
"medium": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-320x180.jpg",
"large": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-640x360.jpg",
"template": "http: //static-cdn.jtvnw.net/previews-ttv/live_user_jojosaysbreee-{width}x{height}jpg"
},
"channel": {
"_links": {
"self": "http: //api.twitch.tv/kraken/channels/jojosaysbreee",
"follows": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/follows",
"commercial": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/commercial",
"stream_key": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/stream_key",
"chat": "http: //api.twitch.tv/kraken/chat/jojosaysbreee",
"features": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/features",
"subscriptions": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/subscriptions",
"editors": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/editors",
"videos": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/videos",
"teams": "http: //api.twitch.tv/kraken/channels/jojosaysbreee/teams"
},
"background": null,
"banner": null,
"broadcaster_language": "en",
"display_name": "JOJOsaysbreee",
"game": "TomClancy'sRainbowSix: Siege",
"logo": "http: //static-cdn.jtvnw.net/jtv_user_pictures/jojosaysbreee-profile_image-26a326e1c867f257-300x300.jpeg",
"mature": true,
"status": "BetaHype<3",
"partner": false,
"url": "http: //www.twitch.tv/jojosaysbreee",
"video_banner": "http: //static-cdn.jtvnw.net/jtv_user_pictures/jojosaysbreee-channel_offline_image-67b08d519585b45f-640x360.jpeg",
"_id": 41382559,
"name": "jojosaysbreee",
"created_at": "2013-03-16T09: 33: 34Z",
"updated_at": "2015-10-01T05: 15: 26Z",
"delay": null,
"followers": 2318,
"profile_banner": "http: //static-cdn.jtvnw.net/jtv_user_pictures/jojosaysbreee-profile_banner-6abce6a882f4f9e4-480.jpeg",
"profile_banner_background_color": "#ffffff",
"views": 15939,
"language": "en"
}
}
}
The response from the code is all the names from "stream":
_id
game
viewers
created_at
video_height
average_fps
is_playlist
_links
preview
channel
What I am trying to accomplish is getting all the associated values after each one of those items but I cannot seem to get it right. I know it needs to iterate deeper but I've tried IEnumerable method and was unsuccessful there also.
Any and all help is much appreciated.
You're selecting all of the property names into a list with this line:
Dim keys As List(Of String) = inner.Properties().[Select](Function(p) p.Name).ToList()
You won't be able to get anything other than the property names from keys this way. Instead, loop over the Properties() collection and examine each JProperty:
For Each prop As JProperty In inner.Properties()
Debug.WriteLine("{0} - {1}", prop.Name, prop.Value)
Next
In addition, I'd recommend a few changes. The code you're using to make the request is harder than it should be :)
Dim sUrl As String = Convert.ToString("https://api.twitch.tv/kraken/streams/") & sUsername
No need to call Convert.ToString("") - it's already a string. And (although it's a matter of opinion), I think Hungarian notation for the variables isn't necessary. This is much simpler:
Dim url As String = "https://api.twitch.tv/kraken/streams/" & username
Much easier to just use WebClient:
Dim client As New WebClient()
client.Headers.Add(HttpRequestHeader.Accept, "application/vnd.twitchtv.v3+json")
Dim responseJson = client.DownloadString(url)
Complete example:
Dim username As String = "???"
Dim url As String = "https://api.twitch.tv/kraken/streams/" & username
Dim client As New WebClient()
client.Headers.Add(HttpRequestHeader.Accept, "application/vnd.twitchtv.v3+json")
Dim responseJson As String = client.DownloadString(url)
Dim outer As JToken = JToken.Parse(responseJson)
Dim inner As JObject = outer("stream").Value(Of JObject)
For Each prop As JProperty In inner.Properties()
Console.WriteLine($"{prop.Name} - {prop.Value}")
Next
Easy peasy! :)

VB.NET need help in deserialization of a JSON

Hey I need help in deserializing this:
{
"success": true,
"rgInventory": {
"2722309060": {
"id": "2722309060",
"classid": "939801430",
"instanceid": "188530139",
"amount": "1",
"pos": 1
},
"2722173409": {
"id": "2722173409",
"classid": "937254203",
"instanceid": "188530139",
"amount": "1",
"pos": 2
},
"2721759518": {
"id": "2721759518",
"classid": "720293857",
"instanceid": "188530139",
"amount": "1",
"pos": 3
},
"2721748390": {
"id": "2721748390",
"classid": "310777652",
"instanceid": "480085569",
"amount": "1",
"pos": 4
}
}
}
at the end it should look like:
2722309060#2722173409#2721759518#2721748390
Dim result = JsonConvert.DeserializeObject(jsonstring) 'deserialize it
Dim tempfo As String = result("rgInventory").ToString 'get rgInventory
Console.WriteLine(tempfo)
how i can deserialize all 'id's?
The json contains a Dictionary of items, the IDs you want are the keys. If you deserialized it, you could get them from the Dictionary. Otherwise, you can use JParse and linq to get them:
Dim jstr As String = ...
' parse the json
Dim js As JObject = JObject.Parse(jstr)
' extract the inventory items
Dim ji As JObject = JObject.Parse(js("rgInventory").ToString)
' get and store the keys
Dim theIds As List(Of String) = ji.Properties.Select(Function(k) k.Name).ToList()
I suspect that when "success" is false that the resulting items list will be empty. Test that it works:
For Each s As String In theIds
Console.WriteLine(s)
Next
Result:
2722309060
2722173409
2721759518
2721748390

JSON - jResults/VB error

I am trying to take the value of a result JSON using VB(JSON.NET).
JSON
"paging": - {
"offset": 0,
"limit": 200,
"total": 6,
},
"results": - [
- {
"user_id": 010101,
"name": "Name X",
"nickname": "XXXX",
"points": 0
},
- {
"user_id": 0222101,
"name": "Name X2",
"nickname": "YYYY",
"points": 0
}
My code:
request = DirectCast(WebRequest.Create(campos.url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp, teste As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
'Dim results As List(Of JToken) = jResults.Children().ToList()
teste = jResults("results")("nickname").ToString()
I need to take the nickname, however do not achieve. In the truth, achieve only take values of the ítem PAGING and any of RESULTS.
But is giving error, he does not achieve to find the values.
Help me?
tks!