Write to file as JSON format?

Question:

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

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

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

The JSON format that I want:

[
 {"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 passed from the method save_fiter_to_JSON.

Asked By: kn3l

||

Answers:

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()
Answered By: steveha

Some tips:

  • you can convert django’s QueryDict to to Python dictionary with dict(keyword_filter) expression,
  • you can add additional record to the dictionary with dict(keyword_filter, name=filter_name) expression.

Then use json module to dump JSON and write it to the file.

Answered By: Denis Otkidach
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.