簡體   English   中英

搜索 JSON,在 JSON 結構中返回字符串

[英]Searching JSON, Returning String within the JSON Structure

我有一組與此類似的 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。

這可能嗎? 我需要先轉換數據嗎? 任何幫助是極大的贊賞!

您不能以 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')使用item['issueKey'].startswith('QTCMP')而不是'QTCMP' in item['issueKey']因為您需要以QTCMP開頭的項目QTCMP 例如,如果值為XXXQTCMP ,則其 id 不應與結果一起出現(但在使用in語句時將結果為True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM