2015-04-17 25 views
0

我有這種格式的日誌文件,分析數據轉化爲JSON文件

{ 
    "box1" : { 
    "item1" : "testValue1", 
    "item2" : "testValue2" 
    }, 
    "foods" : [ 
    { 
     "orange" : "per pound", 
     "price" : 2.99 
    }, 
    { 
     "rice" : "in bag", 
     "price" : 1.99 
     "extra-key" : "extra-Value", 
     "extra-key2" : "extra-Value2", 
    }, 
    { 
     "beer" : "in box", 
     "price" : 12.99 
     "extra-key3" : "extra-Value3" 
     "content" : None 
    } 
] 
} 

,我想下面的值提取到了一個Python輸出文件:

[ "orange" : "per pound", "rice" : "in bag","beer" : "in box" ] 

可有人表演我如何做到這一點?

回答

1

對於讀取json文件,您可以使用Python模塊 - json。它讀取文件並返回存儲在文件中的相應數據結構。

由於您有一本字典,只需索引字典即可輕鬆訪問值。

import json 

with open('logFileName') as f: 
    data = json.load(f) 

# Foods is a list of dictionaries, so you have to access it like that 
print data['foods'][0]['orange'] 

請注意,您錯誤地指定了所需的輸出格式,因爲您正在混合列表和字典語法。實際上,我假設你想從日誌中提取字典。

這是一個問題,如果您事先不知道食物類型將在列表中,因爲要確定字典中的哪個鍵是食物(例如rice)並不容易,哪些是完全不同的,例如extra-key

有關Python的快速入門,請閱讀The Python Tutorial