I would like to parse a JSON data in VBA and check how many books there are. With the hint from GPT, I use this code to parse JSON,
Public Function JsonParse(jsonStr As String) As Object
With CreateObject("HTMLFile")
Set Window = .parentWindow
Window.execScript "var json = " & jsonStr, "JScript"
Set JsonParse = Window.json
End With
End Function
It works fine at first, showed in attached pic, for example, I can get the person's name by debug.print jsonObject.person.name
However, if there are some sub structures like "book", it turns complicated.
I tried debug.print jsonObject.book0.title, jsonObject.book[0].title,jsonObject.book.0.title,jsonObject.book(0).title none of them work.
UBound() doesn't work neither, error message shows that it needs an array...
could you kindly please teach me the syntax on this issue? I would like to know the count of books in this Json so that I could print each title of books.
Thanks in advance!
Here is the demo JSON below:
{
"person": {
"name": "Bob",
"age": 30,
"address": {
"city": "New York",
"zip": 10001
}
},
"book": [
{
"title": "The Catcher in the Rye",
"author": "J.D. Salinger",
"price": 19.99
},
{
"title": "The Lord of the Rings",
"author": "J.R.R. Tolkien",
"price": 29.99
},
{
"title": "Harry Potter and the Philosopher's Stone",
"author": "J.K. Rowling",
"price": 14.99
}
]
}

JsonConverteris a good tool to extract json datahttps://github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas
Output: