Python按displayName过滤JSON记录触发TypeError错误求助
问题:过滤JSON记录时触发
TypeError: string indices must be integers 尝试基于displayName字段值过滤JSON记录,仅保留符合条件的条目,但运行代码时报错:TypeError: string indices must be integers
原代码:
data = { "count": 10408, "value": [ { "id": 151, "name": "Test", "url": "https://url", "build": { "id": "649" }, "isAutomated": True, "owner": { "displayName": "Test Username", "id": "1234" }, "project": { "id": "123", "name": "Research" }, "startedDate": "2018-06-15T20:57:52.267Z", "completedDate": "2018-06-15T20:57:57.813Z", "state": "Completed", "totalTests": 1, "incompleteTests": 0, "notApplicableTests": 0, "passedTests": 1, "unanalyzedTests": 0, "revision": 4, "webAccessUrl": "https://url", "pipelineReference": { "pipelineId": 649, "stageReference": {}, "phaseReference": {}, "jobReference": {} } }, { "id": 151, "name": "Test2", "url": "https://url", "build": { "id": "649" }, "isAutomated": True, "owner": { "displayName": "Some other User", "id": "1234" }, "project": { "id": "123", "name": "Research" }, "startedDate": "2018-06-15T20:57:52.267Z", "completedDate": "2018-06-15T20:57:57.813Z", "state": "Completed", "totalTests": 1, "incompleteTests": 0, "notApplicableTests": 0, "passedTests": 1, "unanalyzedTests": 0, "revision": 4, "webAccessUrl": "https://url", "pipelineReference": { "pipelineId": 649, "stageReference": {}, "phaseReference": {}, "jobReference": {} } } ] } def filterRecords(): filtered = [x for x in data if x["value"]["owner"]["displayName"] == "Test Username"] print(filtered) filterRecords()
错误原因
遍历data时,Python默认遍历字典的键(字符串类型,比如"count"、"value"),此时x是字符串,尝试用x["value"]访问会触发类型错误——字符串只能用整数作为索引。
实际需要遍历的是data["value"]这个列表,列表中的每个元素才是包含owner字段的记录对象。
修正后的代码
data = { # 原data内容不变 } def filterRecords(): # 遍历data["value"]列表,而非data字典 filtered = [x for x in data["value"] if x["owner"]["displayName"] == "Test Username"] print(filtered) filterRecords()
运行后会输出符合displayName: Test Username条件的记录:
[{'id': 151, 'name': 'Test', 'url': 'https://url', 'build': {'id': '649'}, 'isAutomated': True, 'owner': {'displayName': 'Test Username', 'id': '1234'}, 'project': {'id': '123', 'name': 'Research'}, 'startedDate': '2018-06-15T20:57:52.267Z', 'completedDate': '2018-06-15T20:57:57.813Z', 'state': 'Completed', 'totalTests': 1, 'incompleteTests': 0, 'notApplicableTests': 0, 'passedTests': 1, 'unanalyzedTests': 0, 'revision': 4, 'webAccessUrl': 'https://url', 'pipelineReference': {'pipelineId': 649, 'stageReference': {}, 'phaseReference': {}, 'jobReference': {}}}]
内容的提问来源于stack exchange,提问作者JD2775
相关产品推荐
相关产品推荐

