JSON: referencing additional levels

I’ve got this code, which works fine. USD is on a secondary level under quote.

Dim n As JSONItem Dim temp As JSONItem temp = n.value("quote") temp = temp.value("USD")

My question is this. Do I really need to define an additional JSONitem to gain access to the scondary level?
Or can I combine the two lines into one statement, using only the n.value JSONItem?

It entirely depends on the JSON you’re trying to parse. You may wish to review object oriented principles.
If you provide the sample JSON, I’d be happy to help you with formulating the Xojo code to parse it :slight_smile:

Thanks Tim! temp = n.value(“quote”) returns this JSON structure:


Then… from that point, the temp = temp.value(“USD”) returns:


Using a 3rd JSONItem variable, I know I can get at the: price and volume data, but considering best practices, I was thinking I could use just the single n JSONItem, and grab the price in one line of code.

For maintainability, best practice is to take advantage of object oriented design, not try to force it into one line of code. The 1980s are gone, we can name variables with useful names and no longer really need to worry about how many we’re using (until it’s a massive project). Proper scoping helps maintain memory management as well, without needing to focus on it.

This JSON reads like the way it’s formatted allows the API to respond with multiple currencies. This way perhaps you could get both USD and CAD values (if the API does so). With this in mind, you would want to parse all of the objects and then find the USD object to use it. I would even make a class that does so.

This example shows you how to do just that: json_example.xojo_binary_project
I would consider this methodology best practices.

If you have any questions, I’m happy to answer them - I figured it was easiest to tackle this with an example project.

Thanks Tim!! I appreciate the advice. And… the little example you wrote.
I hadn’t considered making it into a class. I will move my existing Methods into a class.
And add that Try…Catch logic looking for JSONException errors.
Interesting… how you made all the variable definitions Properties.