python 以 Json 格式写入文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1960873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:26:56  来源:igfitidea点击:

Write to file as Json format?

pythondjango

提问by kn3l

I have A method for format the ouput as json. My keyword_filter will be pass in this this format:

我有一种将输出格式化为 json 的方法。我的 keyword_filter 将以这种格式传递:

<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']}>

In fact this I got from request.GET (keyword_filter=request.GET)

事实上这是我从 request.GET (keyword_filter=request.GET) 得到的

This is my method:(I am trying)

这是我的方法:(我正在尝试)

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

Everybody here Could help me? The json format That I Want.

这里的每个人都可以帮助我吗?我想要的 json 格式。

[
 {"name": filter_name, "customer_type": "ABC", "tag": [2,3]},
]

Or the other good one format from you .

或者你提供的另一种好的格式。

import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

**filter_name will be pass from the method save_fiter_to_JSON.

**filter_name 将从 save_fiter_to_JSON 方法传递。

Merry Christmas And a happy New Year. ...

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

回答by Denis Otkidach

Some tips:

一些技巧:

  • you can convert django's QueryDictto to Python dictionary with dict(keyword_filter)expression,
  • you can add additional record to the dictionary with dict(keyword_filter, name=filter_name)expression.
  • 您可以QueryDict使用dict(keyword_filter)表达式将 django 转换为 Python 字典,
  • 您可以使用dict(keyword_filter, name=filter_name)表达式将附加记录添加到字典中。

Then use jsonmodule to dump JSON and write it to the file.

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

回答by steveha

Your question is difficult to understand. I am not sure what you need. Here is my best attempt to solve your problem.

你的问题很难理解。我不确定你需要什么。这是我解决您问题的最佳尝试。

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