Python dictionary comes with an extra curly brace as a JSON key via HttpResponse

I am sending specific JSON via a GET request to a Django server. JSON looks like this.

data = {
            test1: [1, 2, 3, 4],
            test2: {
                test21: ['a', 'b'],
                test22: 'data22'
            }
        };

      

Edit 2: Code for sending data:

string = JSON.stringify(data)
url = 'http://127.0.0.1:8000/calc/?' + string
$http.get(url).success(function(response) {console.log(response)});

      

End of edit 2

After I stringify

submit it, I run the following code in the request data.

def calc (request):
    data = request.GET
    z = dict(data.iterlists())
    res = json.dumps(z)
    return HttpResponse(res)

      

The http response looks like this:

Object {{"test1":[1,2,3,4],"test2":{"test21":["a","b"],"test22":"data22"}}: Array[1]}

Array [1] is basically an empty array, so useless. When I change the third line in the code to

z = dict(data.iteritems())

I get the following answer

Object {{"test1":[1,2,3,4],"test2":{"test21":["a","b"],"test22":"data22"}}: ""}

Basically the JSON I require acts as a key to another JSON. I know I can use a method Object.keys()

to retrieve the required JSON, but I would like the answer to be correct.

How do I fix this in python?

Edit 1: I think the error occurs when I convert my data to an element dict

on line 3. I think this is because the operations on z

which should be a dict

are causing the error. For example, it y = z['test1']

throws an error.

+3


source to share


2 answers


The way you submitted your data looks wrong.

When you use GET, the url looks like this:

http://127.0.0.1:8000/?key1=value1&key2=value2

      

What you did above actually makes the json string a key instead of a value . Hence, the request format is incorrect.



I think what you need to do is like:

url = 'http://127.0.0.1:8000/calc/?payload=' + string

      

This will make the payload

key and your actual string a value. And get it:

data = request.GET
json_string = data['payload']
# load the string

      

+2


source


Check out this article .

In particular,

return HttpResponse(res, content_type = "application/json")

      



You are missing a qualifier content_type

.

Also, you really should be using serializers.serialize

like

def calc(request):
  data = request.GET
  return HttpResponse(serializers.serialize("json", data), 
    content_type = 'application/json')

      

+1


source