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?如何更改字典内的格式?这能解决我的问题吗?
这已经使我进一步了很多。但我仍然得到一个“UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ u2018'在位置40:序号不在范围(128)”错误。所以我想我必须以某种方式重新编码JSON?! – Tom