How to fetch only a part of JSON data using swift?

I’m seeking to fetch data from an API JSON format using swift. The API data have the following structure:

{     "Meta Data": {         "1. Information": "Intraday (5min) open, high, low, close prices and volume",         "2. Symbol": "IBM",         "3. Last Refreshed": "2020-08-20 19:05:00",         "4. Interval": "5min",         "5. Output Size": "Compact",         "6. Time Zone": "US/Eastern"     },     "Time Series (5min)": {         "2020-08-20 19:05:00": {             "1. open": "123.2000",             "2. high": "123.2000",             "3. low": "123.2000",             "4. close": "123.2000",             "5. volume": "204"         },         "2020-08-20 18:50:00": {             "1. open": "123.2000",             "2. high": "123.2000",             "3. low": "123.2000",             "4. close": "123.2000",             "5. volume": "100"         },         "2020-08-20 18:45:00": {             "1. open": "123.2000",             "2. high": "123.2000",             "3. low": "123.2000",             "4. close": "123.2000",             "5. volume": "100"         },         "2020-08-20 18:40:00": {             "1. open": "123.1500",             "2. high": "123.1500",             "3. low": "123.1500",             "4. close": "123.1500",             "5. volume": "100"         }     } }   

Question: Is there any way to only fetch the last(latest) e.g. two "Time Series" values?

My detailed problem: The above example ist simplified to only 4 values. In reality, it may have 50.000 values. Until now, my only idea was to fetch all of the data into a dictionary. Since the dictionary can not be sorted, I had to then make a sorted array of tuples from it. Then I must iterate over the array and save only the first x number of elements. Since there are 50.000 values, this process is extremely time, energy, and performance consuming. Therefore it would be best if I would find a method to get the latest x number of data "on the fly".

Add Comment
1 Answer(s)

Question: Is there any way to only fetch the last(latest) e.g. two "Time Series" values?

Answer: No.

To get the most recent record you have to fetch the complete data set anyway.

The date format which is used as dictionary key is sortable. Get the dictionary keys, sort them descending and get the value for the first key.


Please read the documentation of the API. There is an outputsize parameter which can be set to fetch only the latest 100 records (outputsize=compact)

Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.