我有使用csv编写器将json对象写入文件的问题,json对象似乎有多个双引号,因此导致json对象变为无效,这是结果:
"{""user.CustomAttribute.ISOLanguageCode"": ""en"", ""user.Email"": ""emzy1786@googlemail.com""
我想要的是什么
{"user.CustomAttribute.ISOLanguageCode": "en", "user.Email"": "emzy1786@googlemail.com"}
这是我打开文件的方式,也许我可以通过一个参数来防止这种情况发生?
file = csv.writer(open(localResultPath + ".txt",'ab'),delimiter = '|')
这是我写入文件的方式,最后一个追加将json添加为字符串
list.append(pk)
list.append(email)
list.append(json)
file.writerow(list)
解决方法:
使用quoting = csv.QUOTE_NONE关闭自动引用,并将quotechar设置为空字符串:
file = csv.writer(open(localResultPath + ".txt",'ab'),
delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')
即使使用csv.QUOTE_NONE,csv.writer()仍然需要引用quotechar,如果将其设置为除空字符串之外的任何内容(如果存在于值中).默认引号字符是“并且JSON值充满了这些.
演示:
>>> from cStringIO import StringIO
>>> import csv
>>> f = StringIO()
>>> writer = csv.writer(f, delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')
>>> writer.writerow(['{"user.CustomAttribute.ISOLanguageCode": "en"}'])
>>> f.getvalue()
'{"user.CustomAttribute.ISOLanguageCode": "en"}\r\n'
标签:json,python,csv
来源: https://codeday.me/bug/20190612/1225993.html