过滤JSON记录- Python

jei2mxaa  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(89)

我试图过滤掉记录,只显示基于特定列值的JSON格式的记录。在本例中,displayName

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()

字符串
但这是投掷:TypeError: string indices must be integers

j5fpnvbx

j5fpnvbx1#

value是一个列表,而不是一个dict。因为你想遍历列表,而不是数据对象,所以你想为你的 iterable 将范围缩小到value
filtered = [x for x in data["value"] if x["owner"]["displayName"] == "Test Username"]

相关问题