5

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
1
  • Print 'data' and see how it looks. I bet it's a list of dicts, not one dict. Commented Oct 3, 2013 at 7:15

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

oh. Thank you. I am very new to JSON. How about if I want to count the number courses each student take as the sql query above?

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.