Nested json?

Post your questions and help other users.

Moderator: Martin

Post Reply
ariloc
Posts: 109
Joined: 05 Jun 2016 21:36

Nested json?

Post by ariloc » 26 Jul 2017 15:35

Hi, I was trying to get a currency value (from USD to ARS) using Open Exchange Rates API. I use HTTP Request (GET https://openexchangerates.org/api/lates ... id=MYAPPID) to get a JSON response. I have seen several discussions on the forum about JSON and the most near I could get was this in order to get what I want to use:

data = fromJSON(response);
variable = data[0]["ARS"];

However, I could not get it to work as I see that the value I want to get is nested into another one called "rates". How do I do in order to get a nested value.

Sorry for my incomprehensible English and I don't know much about JSON actually.

API documentation: https://docs.openexchangerates.org/

User avatar
Desmanto
Posts: 2709
Joined: 21 Jul 2017 17:50

Re: Nested json?

Post by Desmanto » 27 Jul 2017 02:42

I also don't know much about JSON. Currently I am also trying to digest XML lesson, and need hours just make 2-3 script :(

But if you don't mind the way, you can use Regex to capture the value. I am still learning it, automagic regex tester has been very helpful.

data = findAll(findAll(response, "ARS: \\d+\\.\\d+"), "\\d+\\.\\d+");
ars = data[0];

I know regex can have non capturing group. However, so far I tested in Automagic, i have to capture it twice to remove the non capturing group ("ARS: "). Hopefully someone can show me how. But currently this is my best solution. Result got from findAll() always in list form. So, to access the result in value, we have to get the first element only.
Index of Automagic useful thread List of my other useful posts (and others')
Xiaomi Redmi Note 5 (whyred), AOSP Extended v6.7 build 20200310 Official, Android Pie 9.0, Rooted.

User avatar
Martin
Posts: 4468
Joined: 09 Nov 2012 14:23

Re: Nested json?

Post by Martin » 27 Jul 2017 19:19

Hi,

This is the example JSON provided in the documentation:

Code: Select all

{
    disclaimer: "https://openexchangerates.org/terms/",
    license: "https://openexchangerates.org/license/",
    timestamp: 1449877801,
    base: "USD",
    rates: {
        AED: 3.672538,
        AFN: 66.809999,
        ALL: 125.716501,
        AMD: 484.902502,
        ANG: 1.788575,
        AOA: 135.295998,
        ARS: 9.750101,
        AUD: 1.390866
    }
}
The JSON itself is a map that has the keys disclaimer, timestamp, base and rates. rates itself is also a map with keys AED, AFN etc.

data["rates"] evaluates to the entire map containing all rates so you could write it like this:

Code: Select all

data = fromJSON(response);
rates_map = data["rates"];
variable = rates_map["ARS"];
or the more condensed form without storing the rates map in it's own variable first:

Code: Select all

data = fromJSON(response);
variable = data["rates"]["ARS"];
Regards,
Martin

Post Reply