2014-02-15 22 views
1

我想解析更改JSON數據,但是JSON數據有點複雜並且每次迭代都會發生變化。在Python中解析複雜和變化的JSON數據,深入幾個級別

JSON數據正在一個循環內被解析,所以每次循環運行時,json數據都是不同的。我現在專注於教育數據。

JSON數據:

第一個可能是這樣的:

{u'gender': u'female', u'id': u'15394'} 

下一個可能是:

{ 
u'gender': u'male', u'birthday': u'12/10/1983', u'location': {u'id': '12', u'name': u'Mexico City, Mexico'}, u'hometown': {u'id': u'19', u'name': u'Mexico City, Mexico'}, 

u'education': [ 
{ 
u'school': {u'id': u'22', u'name': u'Institut Saint Dominique de Rome'}, 
u'type': u'High School', 
u'year': {u'id': u'33', u'name': u'2002'} 
}, 
{ 
u'school': {u'id': u'44', u'name': u'Instituto Cumbres'}, 
u'type': u'High School', 
u'year': {u'id': u'55', u'name': u'1999'} 
}, 
{ 
u'school': {u'id': u'66', u'name': u'Chantemerle International School'},  
u'type': u'High School', 
u'year': {u'id': u'77', u'name': u'1998'} 
}, 
{ 
u'school': {u'id': u'88', u'name': u'Columbia University'}, 
u'type': u'College', 
u'concentration': 
[{u'id': u'91', u'name': u'Economics'}, 
{u'id': u'92', u'name': u'Film Studies'}] 
} 
], 
u'id': u'100384'} 

我想回學校所有的值姓名,學校編號和學校類型,所以基本上我需要[education][school][id],[education][school][name],[education][school][type]在一行。但是,每個人都有不同的學校數目,不同類型的學校或根本沒有學校。我想在每個學校的相關名稱,編號和類型上添加一個在現有循環中的新行。

理想輸出

1 34 Boston Latin School High School 
1 26 Harvard University College 
1 22 University of Michigan Graduate School 

在這種情況下,一個指friend_id,我已經設置了追加到列表中的每個循環中的第一項。

我已經試過:

friend_data = response.read() 
friend_json = json.loads(friend_data) 

#This below is inside a loop pulling data for each friend: 

try: 
    for school_id in friend_json['education']: 
     school_id = school_id['school']['id'] 
     friendedu.append(school_id) 
    for school_name in friend_json['education']: 
     school_name = school_name['school']['name'] 
     friendedu.append(school_name) 
    for school_type in friend_json['education']: 
     school_type = school_type['type'] 
     friendedu.append(school_type) 
except: 
    school_id = "NULL" 

打印friendedu writer.writerow(friendedu)

電流輸出:

[u'22', u'44', u'66', u'88', u'Institut Saint Dominique de Rome', u'Instituto Cumbres', u'Chantemerle International School', u'Columbia University', u'High School', u'High School', u'High School', u'College']

這個輸出僅僅是一個它的值列表拉,而是我試圖組織輸出如上所示。我認爲可能需要另一個for循環,因爲對於一個人我希望每個學校都有自己的路線。現在,friendedu列表將一個人的所有教育信息附加到列表的每一行。我希望每個教育項目都在一個新行中,然後轉到下一個人,並繼續爲下一個人寫行。

回答

1

怎麼樣

friend_data = response.read() 
friend_json = json.loads(friend_data) 


if 'education' in friend_json.keys(): 
    for school_id in friend_json['education']: 
     friendedu = [] 
     try: 
      friendedu.append(school_id['school']['id']) 
      friendedu.append(school_name['school']['name']) 
      friendedu.append(school_type['school']['type']) 
     except: 
      friendedu.append('School ID, NAME, or type not found') 
     print(" ".join(friendedu)) 
+0

上面的編輯似乎已經解決了這個問題,謝謝 – kegewe

+0

@kegewe太好了,如果答案對你有用,你會介意接受它作爲解決方案嗎? – Cam

1
import csv 
import json 
import requests 

def student_schools(student, fields=["id", "name", "type"], default=None): 
    schools = student.get("education", []) 
    return ((school.get(field, default) for field in fields) for school in schools) 

def main(): 
    res = requests.get(STUDENT_URL).contents 
    students = json.loads(res) 

    with open(OUTPUT, "wb") as outf: 
     outcsv = csv.writer(outf) 
     for student in students["results"]: # or whatever the root label is 
      outcsv.writerows(student_schools(student)) 

if __name__=="__main__": 
    main() 
+0

的問題是,我最初的嘗試,除了部分是一個很大的一部分較大的循環。我需要從循環的另一部分添加另一個變量到每個'friendedu'行的開頭。我已經將JSON數據拉入friend_json,所以我不必做任何額外的url請求。我只是想將來自每個學生的數據放入'friendedu'列表中的一行或多行。然後,我想將這些1行或更多行添加到之前學生下面的csv文件中。 – kegewe

1

你肯定不需要更多的循環。

人會做:

friendedu = [] 
for school_id in friend_json['education']: 
    friendedu.append("{id} {name} {type}".format(
     id=school_id['school']['id'], 
     name=school_name['school']['name'], 
     type=school_type['school']['type']) 

或列表理解:

friendedu = ["{id} {name} {type}".format(
    id=school_id['school']['id'], 
    name=school_name['school']['name'], 
    type=school_type['school']['type']) for school_id in friend_json['education']] 
+0

我得到關鍵字錯誤:關鍵字arg後的非關鍵字arg – kegewe

+0

我在最後一行遺漏了'type ='。更新。 –