我目前正在为我的类开发一个用python编写的项目,它涉及从服务器获取JSON数据。
我在服务器上的回答看起来像这样但是大约有70万个字符:
{
"jsonrpc": "2.0",
"id": "123",
"result": [{
"id": 666666,
"date": 20170627,
"startTime": 1120,
"endTime": 1140,
"lstype": "bs",
"kl": [],
"su": [],
"ro": [{
"id": 111,
"name": "ROOM_2",
"longname": "NAME_BBB"
}],
"lsnumber": 111,
"statflags": "@"
},
{
"id": 666667,
"date": 20170626,
"startTime": 950,
"endTime": 1035,
"kl": [{
"id": 222,
"name": "CLASS_1",
"longname": "TEACHER_NAME_1, TEACHER_NAME_2"
}],
"su": [{
"id": 33,
"name": "XXX",
"longname": "SUBJECT_1"
}],
"ro": [{
"id": 44,
"name": "ROOM_1",
"longname": "NAME_AAA"
}],
"lsnumber": 55555,
"statflags": "@"
},
{
"id": 666668,
"date": 20170627,
"startTime": 1225,
"endTime": 1310,
"kl": [{
"id": 666,
"name": "CLASS_2",
"longname": "TEACHER_NAME_3"
}],
"su": [{
"id": 777,
"name": "XXX",
"longname": "SUBJECT_2"
}],
"ro": [{
"id": 88,
"name": "ROOM_3",
"longname": "NAME_BBB, NAME_CCC"
}],
"lsnumber": 99999,
"statflags": "@"
},
{
"id": 666669,
"date": 20170627,
"startTime": 1500,
"endTime": 1545,
"kl": [{
"id": 122,
"name": "CLASS_1",
"longname": "TEACHER_NAME_1, TEACHER_NAME_2"
},
{
"id": 133,
"name": "CLASS_3",
"longname": "TEACHER_NAME_5, TEACHER_NAME_6"
},
{
"id": 144,
"name": "CLASS_4",
"longname": "TEACHER_NAME_7 / TEACHER_NAME_8"
}
],
"su": [{
"id": 55,
"name": "XXX",
"longname": "SUBJECT_3"
}],
"ro": [{
"id": 66,
"name": "ROOM_4",
"longname": "NAME_DDD"
}],
"lsnumber": 7777,
"statflags": "@"
}
]
}
我需要在我的JSON文件中获取CLASS_1的所有位置,以便我可以获取相关信息(startTime,endTime,SUBJECT_X,ROOM_X和NAME_XXX)以在我的应用程序中显示它们。
输出应如下所示:
match 1:
950 till 1035
SUBJECT_1
ROOM_1
NAME_AAA
match 2:
1500 till 1545
SUBJECT_3
ROOM_4
NAME_DDD
答案 0 :(得分:1)
甚至不尝试将json解析为字符串 - 使用json
模块将其转换为Python(使用json.loads()
或json.load()
,具体取决于您的源是字符串还是打开的文件),然后迭代生成的对象(在这种情况下为dict
)以获取您的值。
答案 1 :(得分:0)
你可以这样做,
result = []
for item in data['result']:
try:
if item['kl'][0]['name'] == 'CLASS_1':
result.append(['{} till {}'.format(item['startTime'], item['endTime']),
item['su'][0]['longname'], item['ro'][0]['name'],
item['ro'][0]['longname']])
except:
pass
In [11]: result
Out[11]:
[['950 till 1035', 'SUBJECT_1', 'ROOM_1', 'NAME_AAA'],
['1500 till 1545', 'SUBJECT_3', 'ROOM_4', 'NAME_DDD']]
data
将是字典。