I am having issues with writing json objects to a file using csv writer, the json objects seem to have multiple double quotes around them thus causing the json objects to become invalid, here is the result:
"{""user.CustomAttribute.ISOLanguageCode"": ""en"", ""user.Email"": ""emzy1786@googlemail.com""
what I want is
{"user.CustomAttribute.ISOLanguageCode": "en", "user.Email"": "emzy1786@googlemail.com"}
here is how I open the file, perhaps there is an argument I can pass to prevent this from happening?
file = csv.writer(open(localResultPath + ".txt",'ab'),delimiter = '|')
here is how I write to the file, the last append adds the json as a string
list.append(pk)
list.append(email)
list.append(json)
file.writerow(list)
解决方案
Switch off auto-quoting with quoting=csv.QUOTE_NONE, and set quotechar to the empty string:
file = csv.writer(open(localResultPath + ".txt",'ab'),
delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')
Even with csv.QUOTE_NONE the csv.writer() will still want to quote the quotechar if left set to anything but an empty string, if present in the value. The default quote character is " and JSON values are full of those.
Demo:
>>> 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'