1

I have a below json array file with out object. How do I parse it in python. I would like to construct all dataNomTime into a array.

[{
    "id": 8916,
    "objectPaths": ["/thmo/help"],
    "dataTime": 1464961203,
    "dataNomTime": 1464818400,
    "dataEndTime": 1464904800,
    "attribs": null
}, {
    "id": 8917,
    "objectPaths": ["/thmo/help"],
    "dataTime": 1464961203,
    "dataNomTime": 1464818400,
    "dataEndTime": 1464904800,
    "attribs": null
}]

My code

import json
from pprint import pprint

with open('file.json') as data_file:
    data = json.load(data_file)

#pprint(data)
pprint(data["dataNomTime"])

Exception

 pprint(data["dataNomTime"])
TypeError: list indices must be integers, not str

1 Answer 1

3

Since you have a list of dictionaries, data is a list and should be treating as a list.

If you want to extract all the dataNomTime you should do:

nom_times_list = []
for obj in data:
    nom_times_list.append(obj['dataNomTime'])

Or as a list comprehension:

nom_times_list = [obj['dataNomTime'] for obj in data]
Sign up to request clarification or add additional context in comments.

1 Comment

what is the differene betwwen list comprehension and append ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.