简体   繁体   English

如何从python中的JSON文件中选择数据?

[英]how to select data from a JSON file in python?

I have a JSON file like that: 我有一个像这样的JSON文件:

[
{
"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: 这是我在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. 另一个问题:假设JSON文件包含许多具有上述结构的课程。 How can I do something like: 我该怎么做:

Select students, count(course) as course_number from tblstudent
group by students

Your JSON contains a list , with one dictionary in it; 您的JSON包含一个列表 ,其中包含一个字典; 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 . 请注意,您可以通过快速打印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: 使用collections.defaultdict()可以更容易一些:

from collections import defaultdict

courses_per_student = defaultdict(int)

for course in data:
    for student in course['students']:
        courses_per_student[student] += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM