2016-09-30 6 views
1

나는 내가 부르고있는 API에서 다음 JSON 파일이 있습니다 ""14500 "파이썬 톱 레벨의 JSON 지수

{ 
    "14500": [ 
    { 
     "5": { 
     "versionName": "VersionOne", 
     "expand": "executionSummaries", 
     "name": "Regression", 
     "projectId": 15006, 
     "startDate": "", 
     "executionSummaries": { 
      "executionSummary": [] 
     } 
     }, 
     "7": { 
     "versionName": "VersionOne", 
     "expand": "executionSummaries", 
     "versionId": 14500, 
     "projectId": 15006, 
     "startDate": "19/Sep/16", 
     "executionSummaries": { 
      "executionSummary": [] 
     } 
     }, 
     "-1": { 
     "versionName": "VersionOne", 
     "expand": "executionSummaries", 
     "name": "Ad hoc", 
     "modifiedBy": "", 
     "projectId": 15006, 
     "startDate": "", 
     "executionSummaries": { 
      "executionSummary": [] 
     } 
     }, 
     "recordsCount": 3 
    } 
    ], 
    "14501": [ 
    { 
     "-1": { 
     "versionName": "Version 2", 
     "expand": "executionSummaries", 
     "projectId": 15006, 
     "startDate": "", 
     "executionSummaries": { 
      "executionSummary": [] 
     } 
     }, 
     "recordsCount": 1 
    } 
    ], 
} 

내가, 최상위 레벨을 반복해야하고 다음 단계 (예를합니다. 5 ","7 "등)을 사용하여 키와 값을 찾습니다. 예를 들어 전체 JSON 파일을 검색하여 "회귀 분석"과 일치하는 이름을 찾고 "ProjectID"및 기타 문자열에 대한 해당 데이터 세트 집합을 찾아야합니다. 이전에 데이터 [ "level1"] [0] [ "level2"] 등을 사용하여이 작업을 수행했지만,이 경우 숫자는 결코 같지 않으므로 전화하는 법을 모르겠습니다. 여기에 몇 가지 게시물을 살펴본 후 다음을 작성했지만 JSON의 다음 단계가 아닌 한 단계에서만 작동합니다.

request = requests.get(getCyclesURL, headers=headers) 
requestData = json.loads(request.text) 
requestDataKeys = requestData.keys 

for k in requestDataKeys(): 
    dictionaryIDs = requestData[k] 
    for m in requestDataKeys: 
     newDictionaryIDs = requestData[k][m] 
     for dict in newDictionaryIDs: 
      if dict['versionName'] == versionName: 
       versionID = dict['versionID'] 
       print '%s: %s'%(versionName, versionID) 
+0

@MMF 그것은 할당시 메서드를 호출하지 않았으므로 수행합니다. – jonrsharpe

답변

0

다음은 정확한 입력에 맞게 조정 된 부분 스크립트입니다. 적절한 수준에서 name: regression을 찾으면 몇 가지 관련 값을 인쇄합니다.

for k, list_of_dicts in requestData.items(): 
    for d in list_of_dicts: 
     for k, v in d.items(): 
      if isinstance(v, dict) and v.get('name') == "Regression": 
       print '%s: %s %s'%(v.get('projectId'), 
            v.get('versionName'), 
            v.get('versionId')) 
+0

완벽한, 정말 고마워요 !! – JustMe

0
def find_in_dicts(d, key, value): #This finds all dictionaries that has the given key and value 
    for k, v in d.items(): 
     if k == key: 
      if v == value: 
       yield d 
     else: 
      if isinstance(v, dict): 
       for i in find_in_dicts(v, key, value): 
        yield i 
      elif isinstance(v, list) and isinstance(v[0], dict): 
       for item in v: 
        for i in find_in_dicts(item, key, value): 
         yield i 

이 재귀 적 상관없이 데이터 구조를 가져 얼마나 깊은 일 없어야합니다. 나는 그 순간에 그것을 테스트 할 수 없지만, 나는 그것이 탄성으로 당신에게 어떤 생각을 줄 수 있기를 바랍니다.

1

놀랍게도 boltons 라이브러리를 확인하십시오. 그것은 당신의 경우 과잉 될 수있는 remap 기능을 가지고 있지만, 알아두면 좋은 점입니다. 여기에 귀하의 중첩 된 데이터 구조에서 'name': 'Regression' 모든 dicts을 추출하는 우아한 방법이있다 :

from boltons.iterutils import remap 

# Copy your actual data here 
data = {'14500': [{'5': {'name': 'Regression'}, '7': {'name': 'Ad hoc'}}]} 

regressions = [] 

def visit(path, key, value): 
    if isinstance(value, dict) and value.get('name') == 'Regression': 
     # You can do whatever you want here! 
     # If you're here then `value` is a dict 
     # and its `name` field equals to 'Regression'. 
     regressions.append(value) 
    return key, value 

remap(data, visit=visit, reraise_visit=False) 

assert regressions == [{'name': 'Regression'}] 

만 일정 수준에 dicts이 필요하면, 당신은 또한 visit 기능에 path의 길이를 확인할 수 있습니다.