2016-09-14 66 views
1

我有一組JSON數據,看起來simular這樣:搜索JSON,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) 

有了這個,我能夠通過執行數據[「執行」]等方式找到像執行這樣的數據集。我需要做的是在結構中搜索字符串「QTCMP-8」,然後當我找到特定的字符串,找到與該字符串關聯的「id」。所以在QTCMP-8的情況下,它將是ID 17;對於QTCMP-10它將是14.

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

+0

你需要確認與'issueKey'鍵或'projectKey' –

+0

值假設你需要'issueKey',根據你上面提供的例子添加一個答案 –

回答

1

不能在(1),至少它是什麼樣子,現在的O計算爲了做到這一點。以下是每種搜索都具有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'] 

您可能還需要考慮與MongoDB或喜歡的它的工作,如果你正在做沉重的JSON查詢。

+0

使用'dict()'通常不是好的做法 - 使用聲明一個空'dict'的'{}'好得多。 (它不需要名稱查找,它可以進行窺視孔優化,並且該名稱可能被另一個命名不正確的函數或變量等影響)。 –

+0

你也可以將後面的例子寫成dict-comp:'mapping = {d ['issueKey']:d for d in executions ['executions']}' –

+0

@JonClements感謝您指出更好的做法!我會記住這一點。關於理解,我想最好提供更清晰的語法,特別是在OP似乎不太習慣Python的情況下。 – SpiXel

0

一個簡單的迭代與條件將做的工作:

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

# -> 17 
# -> 14 
0

你可以得到所有的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'],因爲你需要的ID以QTCMP開頭的商品。例如,如果值是XXXQTCMP,它的id不應該與目前的結果(但它會導致如True使用in語句)