2009-12-25 83 views
0

我有一种方法将输出格式化为json格式。 我keyword_filter将在此通过这个格式:以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']}> 

其实这个从我得到了request.GET中(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传递。

圣诞快乐,新年快乐。 ...

+0

嗨python,它不是很清楚我什么你想要的。所以你知道你可以使用'simplejson'模块来写入JSON格式。但是问题是什么?难道你需要'filter_name'来写没有引号的事实吗? (因为它被JavaScript解释为对象/函数名称而不是字符串)? – Wim 2009-12-25 09:50:57

+0

是的,事实上,我不使用json,我试图格式化我的输入 给json(很容易)。谢谢 – kn3l 2009-12-25 09:55:58

+0

“simplejson模块写入JSON格式”很好。非常感谢。 – kn3l 2009-12-25 10:13:28

回答

3

一些提示:

  • 你可以转换Django的QueryDict对Python的字典,dict(keyword_filter)表达,
  • 您可以到字典中dict(keyword_filter, name=filter_name)表达增加额外的记录。

然后使用json模块来转储JSON并将其写入文件。

+0

你的想法=>给我的方式 thanksssss – kn3l 2009-12-25 10:43:49

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() 
+0

在我的方法keyword_filter = 将通过。 – kn3l 2009-12-25 10:07:52

+0

谢谢你我从你的代码中得到了一个主意。 :) :) – kn3l 2009-12-25 10:12:44