2012-06-01 3 views
1

1 레벨보다 깊은 JSON 객체를 루프하는 방법을 알 수 없습니다. 목적은 다음과 같습니다Python에서 JSON을 반복하는 방법

{ 
    "data":[ 
    { 
     "id":"251228454889939/insights/page_fan_adds_unique/day", 
     "name":"page_fan_adds_unique", 
     "period":"day", 
     "values":[ 
     { 
      "value":9, 
      "end_time":"2012-05-29T07:00:00+0000" 
     }, 
     { 
      "value":5, 
      "end_time":"2012-05-30T07:00:00+0000" 
     } 
     ], 
     "title":"Daily New Likes", 
     "description":"Daily The number of new people who have liked your Page (Unique Users)" 
    }, 
    { 
     "id":"251228454889939/insights/page_fan_adds/day", 
     "name":"page_fan_adds", 
     "period":"day", 
     "values":[ 
     { 
      "value":9, 
      "end_time":"2012-05-29T07:00:00+0000" 
     }, 
     { 
      "value":5, 
      "end_time":"2012-05-30T07:00:00+0000" 
     } 
     ], 
     "title":"Daily New Likes", 
     "description":"Daily The number of new people who have liked your Page (Total Count)" 
    } 
    ] 
} 

코드 : output_json[data][id] :

def parseJsonData(data): 
    output_json = json.loads(data) 
    for i in output_json: 
     print i 
     for k in output_json[i]: 
      print k 

어떻게 같은 개체에 액세스 할 수 없습니다 와서?

문자열 indice은 붙여 넣은 어떤 정수

답변

2

에게 수 유효 JSON되지 않습니다해야한다 :이하려고하면 는 오류가 발생합니다. "데이터"다음으로는 일치하지 않습니다.

이 정보를 바탕으로 생각해 보면 데이터가 아닌 것 같아요. output_json [data] 값이 목록 인 경우 output_json[data][id]에 액세스 할 수 없습니다. 대신 output_json[data][0][id]과 같은 것을해야합니다. [0]은 목록의 첫 번째 항목에 액세스합니다.

+0

임 확인이 OP를위한 유효한 json, 그러나 OP는 방금 t 조각을 게시했습니다. 그는 전체적인 것입니다. – jdi

+0

들여 쓰기 및 브라켓 팅을 기반으로 한 것처럼 보이지 않습니다. 맨 아래에 브래킷으로 닫혀있는 상단에 열린 브래킷이 있지만, 그 사이에는 가장 일치하지 않는 것이 발생합니다. 슬라이스 일 수도 있지만, 그렇다면 불연속이거나 그렇지 않은 형식의 슬라이스 일 수 있습니다. – BrenBarn

+0

마지막'}'앞에']'를 추가하면됩니다. 들여 쓰기는 중요하지 않습니다. – jdi

5

"데이터"키는 실제로 개체 목록이므로 항목의 "id"필드를 사용하여 항목에 직접 액세스 할 수 없습니다. 싶은 것은 키와 "ID"필드에서 "데이터"의 회원 인덱스 할 수있는 경우,
output_json["data"][0]["id"]

이제 : 당신은 같은리스트 인덱스에 의해 각 항목에 액세스 할 필요가 인덱스와 객체 사이의 실제 상관 관계가 없기 때문에,

# make "data" a dict {id: item, }, instead of list [item1, item2, ...] 
output_json['data'] = dict((item['id'], item) for item in json_data['data']) 

print output_json['data'] 
# {'251228454889939/insights/page_fan_adds_unique/day': ... 

print output_json['data']['251228454889939/insights/page_fan_adds_unique/day'] 
# {'description': 'Daily The number of new p ... 

# ways to loop over "data" 
for id_, item in output_json['data'].iteritems(): 
    print id_, item 

for item in output_json['data'].itervalues(): 
    print item 

그렇지 않으면 당신이해야 할 것은 "데이터"를 통해 단지 루프는 다음과 같습니다 : 당신은 당신의 데이터를 포맷 할 수

for item in output_json["data"]: 
    print item['id'] 

# 251228454889939/insights/page_fan_adds_unique/day 
# 251228454889939/insights/page_fan_adds/day 
관련 문제