搜索JSON,返回JSON结构中的字符串

2024-05-04 19:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组JSON数据,看起来与此类似:

{"executions": [
{
  "id": 17,
  "orderId": 16,
  "executionStatus": "1",
  "cycleId": 5,
  "projectId": 15006,
  "issueId": 133038,
  "issueKey": "QTCMP-8",
  "label": "",
  "component": "",
  "projectKey": "QTCMP",
  "executionDefectCount": 0,
  "stepDefectCount": 0,
  "totalDefectCount": 0
},
{
  "id": 14,
  "orderId": 14,
  "executionStatus": "1",
  "cycleId": 5,
  "projectId": 15006,
  "issueId": 133042,
  "issueKey": "QTCMP-10",
  "label": "",
  "component": "",
  "projectKey": "QTCMP",
  "executionDefectCount": 0,
  "stepDefectCount": 0,
  "totalDefectCount": 0
    }
  ],
  "currentlySelectedExecutionId": "",
  "recordsCount": 4
}

我已经用Python将其解析如下:

import json
import pprint

with open('file.json') as dataFile:
    data = json.load(dataFile)

有了它,我可以通过执行data[“executions”]等来找到执行之类的数据集。。我需要做的是在结构中搜索字符串“QTCMP-8”,然后在找到特定字符串时,找到与该字符串关联的“id”。因此,在QTCMP-8的情况下,它将是id 17;对于QTCMP-10来说是14

这可能吗?我需要先转换数据吗?非常感谢您的帮助


Tags: 数据字符串idjsonlabelcomponentprojectkeyprojectid
3条回答

你不能按照O(1)的计算顺序来做,至少现在是这样。以下是每个搜索的O(n)复杂度的解决方案

id = None
for dic in executions:
    if dic['issueKey'] == query:
        id = dic['id']
        break

在O(1)中执行此操作时,需要对O(n)进行预处理,在预处理中,您可以按它们的issueKey对执行进行分类,并在其中保存所需的任何信息

# Preprocessing of O(n)
mapping = dict()
for dic in executions:
    mapping[dic['issueKey']] = {
        'id':  dic['id'],
        'whatever': 'whateverel'
    }

# Now you can query in O(1)

return dic[query]['id']

如果要进行大量的json查询,您可能还需要考虑使用MongoDB或类似的工具

有条件的简单迭代可以完成这项工作:

for execution in data['executions']:
    if "QTCMP" in execution['issueKey']:
        print(execution["id"])

# -> 17
# -> 14

您可以获取所有ID的列表,如下所示:

>>> [item['id'] for item in my_json['executions'] if item['issueKey'].startswith('QTCMP')]
[17, 14]

其中my_json是存储JSON结构的变量

注意:我使用的是item['issueKey'].startswith('QTCMP')而不是'QTCMP' in item['issueKey'],因为您需要以QTCMP开头的项的id。例如,如果值是XXXQTCMP,那么它的id不应该出现在结果中(但在使用in语句时,它将作为True出现)

相关问题 更多 >