2015-10-24 88 views
0

我想一個文件(不是真的JSON)轉換成csv文件,這裏是代碼轉換JSON到CSV

import json 
import gzip 
import csv 


def parse(path): 
    g = gzip.open(path, 'r') 
    for l in g: 
    yield json.dumps(eval(l)) 


csvOut = gzip.open("meta_Musical_Instruments.csv", 'w') 
writer = csv.writer(csvOut) 

fields = ["asin"] 

for product in parse("meta_Musical_Instruments.json.gz"): 
    line = [] 
    for f in fields: 
    if product.has_key(f): line.append(product[f]) 
    else: line.append("") 
    writer.writerow(line) 

示例文件是這樣的:

{'asin': '0014072149', 'related': {'also_viewed': ['B0058DK7RA'], 'buy_after_viewing': ['B0058DK7RA']}, 'title': 'Double Concerto in D Minor By Johann Sebastian Bach. Edited By David Oistrach. For Violin I, Violin Ii and Piano Accompaniment. Urtext. Baroque. Medium. Set of Performance Parts. Solo Parts, Piano Reduction and Introductory Text. BWV 1043.', 'price': 18.77, 'salesRank': {'Musical Instruments': 94593}, 'imUrl': 'http://ecx.images-amazon.com/images/I/41m6ygCqc8L._SY300_.jpg', 'brand': '', 'categories': [['Musical Instruments']], 'description': 'Composer: J.S. Bach.Peters Edition.For two violins and pianos.'} 

後,我執行代碼,我得到這個錯誤消息:

--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-14-1cb41fc12b41> in <module>() 
    16 line = [] 
    17 for f in fields: 
---> 18  if product.has_key(f): line.append(product[f]) 
    19  else: line.append("") 
    20 writer.writerow(line) 

AttributeError: 'str' object has no attribute 'has_key' 

請幫助!

+1

'json.dumps(eval(l))'什麼是什麼? –

+0

請提取一個最簡單的例子。硬編碼的文件內容。 –

+0

呃,問題是......最明顯的。我喜歡瞭解提問者有時在想什麼,以便我可以給出完整的答案。 –

回答

-1

使用雙引號而不是單引號。 JSON只允許雙引號

'key' - >"key"

+0

是的,提問者已經注意到輸入不是JSON。 –

+0

那麼他解析JSON,所以當他提供非JSON對象的程序時,它變得不高興 –

+0

他們其實不是。此外,不管這個錯誤是不是抱怨。 –

0

你似乎是無所適從json.dumps()呢...... JSON是一種文本格式 - 數據的文本表示。 json模塊可讓您將Python對象編碼爲json或將json字符串解碼爲Python對象。 json.dumps(python_obj)將Python編碼爲json並返回一個字符串。要從json字符串解碼爲Python對象,您必須使用json.loads(json_string)。督察,你`parse()函數應該像這樣:

def parse(path): 
    g = gzip.open(path, 'r') 
    for l in g: 
    yield json.loads(l) 

我不能告訴它是否會不知道你的「不是真的JSON」文件中包含的工作,這絕對應該如何使用json將一個json字符串解碼爲一個Python對象;)

附註:Python中eval()的實際使用情況非常非常罕見 - 自1.5.2天以來,我一直在使用Python進行編程,從來沒有到目前爲止,使用它 - ,所以如果你發現自己使用eval有99.999%的機會你做錯了。