如何以JSON格式写入文件?
我有一个方法可以把输出格式化成JSON。
我的关键词过滤器会以这种格式传入:
<QueryDict: {u'customer_type': [u'ABC'], u'tag': [u'2']}>
<QueryDict: {u'customer_type': [u'TDO'], u'tag': [u'3']}>
<QueryDict: {u'customer_type': [u'FRI'], u'tag': [u'2,3']}>
实际上,这是我从请求中获取的(keyword_filter=request.GET)。
这是我的方法:(我正在尝试)
def save_fiter_to_JSON(self, dest, keyword_filter):
fwrite = open(dest, 'a')
#keyword_filter = <QueryDict: {u'customer_type': [u'FRI'], u'tag': [u'2,3']}>
string_input1 =string.replace(str(keyword_filter), '<QueryDict:', '["name:"')
string_input2 = string.replace(string_input1, '>', '')
fwrite.write(string_input2+",\n")
fwrite.close()
我想要的JSON格式是:
[
{"name": filter_name, "customer_type": "ABC", "tag": [2,3]},
]
或者你们提供的其他好的格式。
import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
filter_name将会从方法save_fiter_to_JSON中传入。
2 个回答
2
你的问题有点难懂。我不太确定你需要什么。以下是我尽力为你解决问题的尝试。
def save_fiter_to_JSON(self, dest, filter_name, keyword_filter):
# start with an empty list
lst = []
# I don't know where you will get your qd (QueryDict instance)
# filter something using keyword_filter? Replace this with actual code
for qd in ??FILTER_SOMETHING??(keyword_filter):
# make a mutable copy of the QueryDict
d = qd.copy()
# update the copy by adding "name"
d["name"] = filter_name
# append dict instance to end of list
lst.append(d)
# get a string with JSON encoding the list
s = json.dumps(lst)
f = open(dest, 'a')
f.write(s + "\n")
f.close()
3
一些小提示:
- 你可以把Django的
QueryDict
转换成Python字典,方法是用dict(keyword_filter)
这个表达式。 - 你还可以通过
dict(keyword_filter, name=filter_name)
这个表达式,往字典里添加额外的记录。
然后使用 json
模块来生成JSON格式的数据,并把它写入文件中。