Reputation: 599
I have a JSON file like that:
[
{
"course": "CMPT 102 D1",
"instructor": "hamarneh",
"students": [
"axc5",
"csf10",
"ctu1",
"nmw15",
"nsm12",
"ppy1",
"qtg13",
"tim1",
"tkd10",
"vhm8",
"vsv1",
"wps1",
"xup12",
"yqt6"
],
"title": "Scientific Cmpt.Prgm"
}]
and here is my code in python:
import json
json_data=open('jsonfile')
data=json.load(json_data)
print(data['students'])
but it shows an error:
print(data['students'])
TypeError: list indices must be integers, not str
please help!
And another question: Assume that the JSON file contains many courses with the structure like above. How can I do something like:
Select students, count(course) as course_number from tblstudent
group by students
Upvotes: 5
Views: 15878
Reputation: 1122122
Your JSON contains a list, with one dictionary in it; there are two square brackets, [
and ]
, around the dictionary.
Select the first element:
print(data[0]['students'])
Quick demo:
>>> print(data)
[{'instructor': 'hamarneh', 'course': 'CMPT 102 D1', 'title': 'Scientific Cmpt.Prgm', 'students': ['axc5', 'csf10', 'ctu1', 'nmw15', 'nsm12', 'ppy1', 'qtg13', 'tim1', 'tkd10', 'vhm8', 'vsv1', 'wps1', 'xup12', 'yqt6']}]
>>> print(data[0]['students'])
['axc5', 'csf10', 'ctu1', 'nmw15', 'nsm12', 'ppy1', 'qtg13', 'tim1', 'tkd10', 'vhm8', 'vsv1', 'wps1', 'xup12', 'yqt6']
Note that you could have spotted this yourself with a quick print of just data
.
If this was a list of multiple courses and you need to count per-student, set up a dictionary keyed on students, containing integers. Using collections.defaultdict()
makes that a little easier:
from collections import defaultdict
courses_per_student = defaultdict(int)
for course in data:
for student in course['students']:
courses_per_student[student] += 1
Upvotes: 5