我需要创建一个像["a", "b", "c", "d"]
我正在尝试按如下方式创建
import json
with open('djs.json', 'w') as outfile:
for dj in DJ.objects.all():
json.dump(str(dj), outfile, separators=(',', ': '))
这会产生类似"a","b","c","d"
这样做的正确方法是什么?
答案 0 :(得分:3)
这个怎么样:
lst = [str(dj) for dj in DJ.objects.all()]
with open('data.txt', 'w+') as outfile:
json.dump(lst, outfile)
如果您的__unicode__
是单个字段,您甚至可以
json_dump = json.dump(list(Dj.objects.values_list('field', flat=True)))