2014-05-14 157 views
0

我有一個包含讀取數據

[{ 
     'address': 'Bramalea, L6T 0E2' 
     'type': 'home' 
     }, { 
     'address': 'A, 46 Peel Drive, ASDF23' 
     'type': 'office' 
     } 
}] 

我只是想讀地址型辦公 S3文件,任何機構可以建議我怎麼可以遍歷這個數據?因爲它只是一個字符串 到目前爲止,我能夠讀取該數據

conn = S3Connection(AWS_KEY, AWS_SECRET) 
bucket = conn.get_bucket(BUCKET_NAME) 
for key in bucket.list(DIR_Name): 
    data = key.get_contents_as_string() 
    print data 

我也嘗試讀取數據使用JSON模塊

data = key.get_contents_as_string() 
print json.loads(data) 

其提高

print json.loads(data) 
    File "/usr/lib/python2.7/json/__init__.py", line 326, in loads 
    return _default_decoder.decode(s) 
    File "/usr/lib/python2.7/json/decoder.py", line 366, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode 
    obj, end = self.scan_once(s, idx) 
ValueError: Expecting property name: line 2 column 5 (char 8) 
+1

不需要抱歉提問。但是,你應該真實地展示你到目前爲止已經嘗試過的內容,以便我們知道你已經提出了一些想法。這就是說,我會建議閱讀關於['json'](https://docs.python.org/3/library/json.html)模塊。 – ubomb

+1

這是JSON數據嗎?它看起來像。你可以使用'json'庫來讀入這個文件,然後按你想要的進行過濾。 – CoryKramer

+0

@ubomb問題已更新 – user3638022

回答

0

這是沒有必要使用其他模塊。由於這是一個字典列表,很容易只保留元素與'type''office'

my_list = [{ 
    'address': 'aa, 46 Peel Centre Drive, A342', 
    'type': 'home', 
    }, { 
    'address': 'a, 46 Peel Centre Drive, AS32', 
    'type': 'office', 
    }, { 
    'address': 'b, 46 Peel Centre Drive, SD22', 
    'type': 'home', 
    }, { 
    'address': 'c, 46 Peel Centre Drive, SD22', 
    'type': 'home', 
    }, { 
    'address': 'd, 46 Peel Centre Drive, SSD222', 
    'type': 'office', 
    }] 
addresses = [elem['address'] for elem in my_list if elem['type'] == 'office'] 
print addresses 
0

我就在我到您的文章評論不正確。請勿使用json模塊解析此文件,因爲這不是有效的json。有效的json只在其字符串周圍使用雙引號 - 而不是單引號。相反,這看起來像基本的python文字結構(讀取:基本的python數據類型)。有一種方法可以安全地做到這一點與潛在的不受信任的來源。 ast.literal_eval應該可以在這裏幫助你。