I would like to iterate over the items in the json shown below. Not every item has all the same fields/key values.
The items I want to iterate over are found at "items":
How do I iterate over these items?
I can get the items into an array called Items:
Dim ParseJson As JObject = JObject.Parse(APIReturn)
Dim Items = ParseJson.SelectToken("items").ToString()
How can I iterate over this array, and extract the values from each item?
As I get each item, I want to extract the "title", "date", and "category". How do get these values from the json?
{
"title": "Massapequa Park July 2023",
"date": "2023-07-01T20:52:43.581Z",
"location": {
"title": "Massapequa Park, New York, USA",
"city": "Massapequa Park",
"tzid": "America/New_York",
"latitude": 40.68038,
"longitude": -73.45512,
"cc": "US",
"country": "United States",
"admin1": "New York",
"asciiname": "Massapequa Park",
"geo": "geoname",
"geonameid": 5126187
},
"range": {
"start": "2023-07-01",
"end": "2023-07-08"
},
"items": [
{
"title": "Holiday 1",
"date": "2023-07-01",
"hdate": "H1",
"category": "Holiday ",
},
{
"title": "Meeting: 9:19pm",
"date": "2023-07-01T21:19:00-04:00",
"category": "Meeting",
"title_orig": "Meeting",
},
{
"title": "MiniFast begins",
"date": "2023-07-06T03:42:00-04:00",
"category": "fast",
"subcat": "mini fast",
"memo": "short fast"
},
{
"title": "Stop Mini Fast",
"date": "2023-07-06",
"hdate": "Hold 1",
"category": "fast",
"subcat": "mini fast",
"memo": "short fast"
},
{
"title": "Fast ends",
"date": "2023-07-06T21:08:00-04:00",
"category": "Light",
"subcat": "fast",
"memo": "Old Shirt"
},
{
"title": "18 Before Dusk: 8:09pm",
"date": "2023-07-07T20:09:00-04:00",
"category": "Ready Lights",
"title_orig": "18 Before Dusk",
"memo": "Nachos"
},
{
"title": "Holiday 7",
"date": "2023-07-08",
"hdate": "7th Holiday",
"category": "Holiday ",
},
{
"title": "Meeting: 9:17pm",
"date": "2023-07-08T21:17:00-04:00",
"category": "Meeting",
"title_orig": "Meeting",
}
]
}
2
Answers
Assuming you’re using
Newtonsoft.Json
, then it’s simple-enough:JToken.Parse
on the response body (APIReturn
) and then verify the parsedJToken
is anJObject
(as it could be anull
literal, or aJArray
, or something else).JObject.Property("items")
to get theJProperty
for the"items":
property.JProperty.Value
is aJArray
(as opposed tonull
or anotherJObject
or something else).JTokens
in thatJArray
: test each one to verify it’s aJObject
(or use Linq’sOfType<JObject>()
) and then safely extract the desired values.Something like this:
Screenshot proof:
(Ignore how LinqPad reports the ValueTuple member names as
Item1
,Item2
, andItem3
: C# IntelliSense will let you correctly dereference those members by the namestitle
,date
, andcategory
in code).you can use this code