Python Forum

Full Version: Print a JSON file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like to print just the date and value?
import json

# read file
with open('resting_heart_rate-2014-02-28.json') as json_file:
    data = json.load(json_file)
    for p in data['dateTime']:
        print('json_file')
fault when running the script:
Error:
PS C:\Users\Downloads\heart> C:/Users/erorobi/AppData/Local/Continuum/anaconda3/Scripts/activate PS C:\Users\Downloads\heart> conda activate base conda : The term 'conda' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + conda activate base + ~~~~~ + CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Downloads\heart> & C:/Users/AppData/Local/Continuum/anaconda3/python.exe "c:/Users/Downloads/heart/read json.py" Traceback (most recent call last): File "c:/Users/Downloads/heart/read json.py", line 6, in <module> for p in data['dateTime']: TypeError: list indices must be integers or slices, not str PS C:\Users\Downloads\heart>
json file format:
Output:
[{ "dateTime" : "02/27/15 00:00:00", "value" : { "date" : "02/27/15", "value" : 75.0, "error" : 9.0 } }]
The error is because you are trying to access something in a list as if its a dict.
data is a list with a single item in that's a dict.
if you was to print data you would get the following
...
data = json.load(json_file)
print(data)
...
Output:
[{'dateTime': '02/27/15 00:00:00', 'value': {'date': '02/27/15', 'value': 75.0, 'error': 9.0}}]
you need to iterate data directly and then use the 'dateTime' key on each iterated item.
thank you for the update, i changed the code to:

import json

# read file
with open('resting_heart_rate-2014-02-28.json') as json_file:
    data = json.load(json_file)
    for p in data['dateTime']:
print('dateTime')
Error from the change on line 7
Error:
File "", line 7 print('dateTime') ^ IndentationError: expected an indented block
The print has to be indented into the for loop like you had it before.
Remove the "key" 'dateTime' from data and then print p's 'dateTime' key(p will be each item in the list which at the moment is one dict).
Sorry Yoriz, I'm really new to this.

Would you have an example of what your explaining?

Thanks for the help!!!
Example of iterating a list
items = [{"one": 1}]

for item in items:
    print(item)
Output:
{'one': 1}
Example of accessing a dict item by its key
mydict = {"one": 1}
print(mydict["one"])
Output:
1