2016-02-27 48 views
1

我有一個很大的文件,其中包含有效的嵌套json在每一行上,每個json看起來像(真實數據要大得多,所以這個json的和平將會顯示爲插圖只是):.get嵌套json的方法不起作用

 {"location":{"town":"Rome","groupe":"Advanced", 
      "school":{"SchoolGroupe":"TrowMet", "SchoolName":"VeronM"}}, 
      "id":"145", 
      "Mother":{"MotherName":"Helen","MotherAge":"46"},"NGlobalNote":2, 
      "Father":{"FatherName":"Peter","FatherAge":"51"}, 
      "Study":[{ 
      "Teacher":["MrCrock","MrDaniel"], 
      "Field":{"Master1":["Marketing", "Politics", "Philosophy"], 
      "Master2":["Economics", "Management"], "ExamCode": "1256"} 
      }], 
      "season":["summer","spring"]} 

我需要解析這個文件,以從每一個JSON只提取了一些鍵值,獲取應該是一個數據幀:

Groupe  Id MotherName FatherName Master2 
Advanced 56 Laure   James  Economics, Management 
Middle  11 Ann   Nicolas  Web-development 
Advanced 6 Helen   Franc  Literature, English Language 

我用method proposed me in the other question.get但它不起作用無線TH嵌套的JSON,所以例如,如果我嘗試:

def extract_data(data): 
    """ convert 1 json dict to records for import""" 
    dummy = {} 
    jfile = json.loads(data.strip()) 
    return (
    jfile.get('Study', dummy).get('Field', np.nan).get('Master1',np.nan), 
    jfile.get('location', dummy).get('groupe', np.nan)) 

此行jfile.get('Study', dummy).get('Field', np.nan).get('Master1', np.nan)它將引發我一個錯誤:

AttributeError: 'list' object has no attribute 'get'

這顯然是因爲的"Study"值不是一本字典,既不名單,但一個有效的json!我該如何處理這個問題?是否存在一種類似於.get的方法,但對於json?我想還有另外一個選擇:解碼這個json,然後用.get解析它,但問題在於它是另一個json的核心,所以我不知道如何解碼它!

+0

而不是鏈接到'GET'您可以檢查是否最後一次通話如果'Master1'的值不是一個列表,你在'Master1'鍵下得到的是一個列表,然後獲得所有列表值或一個單一值。 –

+0

順便說一句,你可以糾正'get('Master1' 'np.nan)'到'get('Master1',np。南)'在你的文章? –

+0

@YannisP。請問您能更準確地說明我可以如何實施它嗎?和平的代碼,方法? – Amanda

回答

3

Data是有效的JSON格式化字符串。 JSON包含四個基本要素:

  • 對象:用大括號{}
  • 陣列定義:用大括號[]定義
  • :可以是,一個對象陣列,或文字真
  • 字符串:用雙引號定義,包含Unicode字符或共同backslash escapes


使用json.loads將轉換string成python object遞歸。這意味着每個內部的JSON元素將被表示爲python object

因此: jfile.get('Study') --->python list


要檢索Field你應該遍歷研究列表:

file = json.loads(data.strip()) 
study_list = jfile.get('Study', []) # don't set default value with different type 
for item in study_list: 
    print item.get('Field') 
+0

ow來解決這個問題,謝謝!我明白了,但在這種情況下,我如何從這個列表中提取值? – Amanda

+0

哦,它就像'l = jfile.get.get('Study',dummy)'然後'l [0]'給你第一個元素,或者你可以寫一個迭代。看到這裏的例子:http://www.tutorialspoint.com/python/python_lists.htm –

+1

@Forge優秀的解釋和解決方案!非常感謝你! – Amanda