free_road
free_road

Reputation: 21

How to iterate and extract data from this specific JSON file example

I'm trying to extract data from a JSON file with Python.

Mainly, I want to pull out the date and time from the "Technicals" section, to put that in one column of a dataframe, as well as pulling the "AKG" number and putting that in the 2nd col of the dataframe. Yes, I've looked at similar questions, but this issue is different. Thanks for your help.

A downNdirty example of the JSON file is below:

    { 'Meta Data': { '1: etc'
                     '2: etc'},
      'Technicals': { '2017-05-04 12:00': {  'AKG': '64.8645'},
                      '2017-05-04 12:30': {  'AKG': '65.7834'},
                      '2017-05-04 13:00': {  'AKG': '63.2348'}}}

As you can see, and what's stumping me, is while the date stays the same the time advances. 'AKG' never changes, but the number does. Some of the relevant code I've been using is below. I can extract the date and time, but I can't seem to reach the AKG numbers. Note, I don't need the "AKG", just the number.

I'll mention: I'm creating a DataFrame because this will be easier to work with when creating plots with the data...right? I'm open to an array of lists et al, or anything easier, if that will ultimately help me with the plots.

    akg_time = []
    akg_akg = []
    technicals = akg_data['Technicals']  #akg_data is the entire json file

    for item in technicals:  #this works
         akg_time.append(item)

    for item in technicals:  #this not so much
         symbol = item.get('AKG')
         akg_akg.append(symbol)

    pp.pprint(akg_akg)
    error: 'str' object has no attribute 'get'

Upvotes: 0

Views: 189

Answers (2)

Anton vBR
Anton vBR

Reputation: 18916

Although Coldspeed answer is right: when you have a dictionary you loop through keys and values like this:

Python 3

for key,value in technicals.items():
     akg_time.append(key)
     akg_akg.append(value["akg"])

Python 2

for key,value in technicals.iteritems():
     akg_time.append(key)
     akg_akg.append(value["akg"])

Upvotes: 1

cs95
cs95

Reputation: 402593

You've almost got it. You don't even need the second loop. You can append the akg value in the first one itself:

for key in technicals: # renaming to key because that is a clearer name
     akg_time.append(key)
     akg_akg.append(technicals[key]['AKG'])

Your error is because you believe item (or key) is a dict. It is not. It is just a string, one of the keys of the technicals dictionary, so you'd actually need to use symbols = technicals[key].get('AKG').

Upvotes: 1

Related Questions