2013-07-10 118 views
1

我想將JSON文件選擇性地轉換爲CSV。這意味着我想遍歷JSON。使用Python將JSON轉換爲CSV

的代碼來寫我的CSV看起來是這樣的:

f = csv.writer(open("test.csv", "wb+")) 
f.writerow(["id", "text", "polarity"]) 
for x in final: 
    f.writerow([x["id"], 
       x["text"], 
       x["polarity"]]) 

可悲的是,我得到以下錯誤:

TypeError: string indices must be integers 

我已經有一個想法是什麼問題。加載後我檢查了我的JSON的類型。這是一個字典,應該沒問題。

當我打印我的字典:

print (final) 

我得到:

{u'data': [{u'polarity': 2, u'text': u'How deep is your love - Micheal Buble Ft Kelly Rowland ?', u'meta': {u'language': u'en'}, u'id': u'1'}, {u'polarity': 2, u'text': u'RT @TrueTeenQuotes: #SongsThatNeverGetOld Nelly ft. Kelly Rowland - Dilemma', u'meta': {u'language': u'en'}, u'id': u'2'}, {u'polarity': 2, u'text': u'RT @GOforCARL: Dilemma - Nelly Feat. Kelly Rowland #Ohh #SongsThatNeverGetOld', u'meta': {u'language': u'en'}, u'id': u'3'}, {u'polarity': 2, u'text': u'#NP Kelly Rowland Grown Woman', u'meta': {u'language': u'en'}, u'id': u'4'}, {u'polarity': 2, u'text': u"My friend just said 'kelly rowland is gettin it good... Most of her songs are sexual'", u'meta': {u'language': u'en'}, u'id': u'5'}, {u'polarity': 2, u'text': u'No. Kelly Rowland is the Black Barbie, idc', u'meta': {u'language': u'en'}, u'id': u'6'}, {u'polarity': 2, u'text': u'Nelly - Gone ft. Kelly Rowland http://t.co/tXjhCS05l0', u'meta': {u'language': u'en'}, u'id': u'7'}, {u'polarity': 2, u'text': u'Kisses Down Low by Kelly Rowland killer?\u2018?\u2018?\u2018 #NellyVille', u'meta': {u'language': u'en'}, u'id': u'8'}]} 

如果每個項目似乎是Unicode除了爲 '極' 的價值。我現在有3個問題。 1.所有項目是否應該使用unicode?如何更改字典內的格式?這能解決我的問題嗎?

回答

1

迭代Python中的字典爲您提供了字典的鍵作爲字符串 - 從而x在你上面的例子將僅包含字符串"data"

如果你想遍歷類型的字典中關聯到u"data"列表值final字典的鑰匙,你必須寫在Python中:

... 
for x in final[u"data"]: 
    f.writerow([x["id"], 
       x["text"], 
       x["polarity"]]) 
+0

這已經使我進一步了很多。但我仍然得到一個「UnicodeEncodeError:'ascii'編解碼器無法編碼字符u'\ u2018'在位置40:序號不在範圍(128)」錯誤。所以我想我必須以某種方式重新編碼JSON?! – Tom