简体   繁体   中英

Django deserialization error: string indices must be integers

I'm new to json, Python and Django. I did some research online but none solves my issue. Thanks in advance for any insights!

I am building a system that allows mobile devices to update the server's database, which is managed by Django. I am currently only testing on my local machine where I send a request to a url Django recognizes.

The 1st step I have a piece of python code that tries to communicate with the server.

# in test.py:
data =  '''{"pk": 4, "model": "arts"}'''
data = json.loads(data)
data = json.dumps(data)

URL = "my local host's URL"
h = httplib2.Http(".cache")   
resp, content = h.request(URL, "POST", body = data)

Then at the server the view function is called.

# in views.py:
def Updates(request, category):

    if request.method=='POST':

        print 'Data: %s' % request.body  
        ## this prints successfully: 
        ## > Data: {"pk": "4", "model": "arts"}

        resultJson = serializers.deserialize('json', request.body)

        for obj in resultJson:
            print "OK"

        return HttpResponse(request.body)

    else:
        return HttpResponse("Wrong Method")

The error message I got is:

    Django Version:     1.6.2
    Exception Type:     DeserializationError
    Exception Value:    string indices must be integers
    ...

    Traceback Switch to copy-and-paste view

C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
             response = wrapped_callback(request, *callback_args, **callback_kwargs)

C:\Python27\lib\site-packages\django\views\decorators\csrf.py in wrapped_view
            return view_func(*args, **kwargs)

C:\pathToViewsFile\views.py in Updates
              for obj in resultJson:


C:\Python27\lib\site-packages\django\core\serializers\json.py in Deserializer
            six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])


C:\Python27\lib\site-packages\django\core\serializers\json.py in Deserializer
            for obj in PythonDeserializer(objects, **options):

C:\Python27\lib\site-packages\django\core\serializers\python.py in Deserializer
            Model = _get_model(d["model"])

As shown in the example JSON file Django's doc provides (that's the last place I checked, actually), deserialize takes a list of dictionnaries (which should have a fields key, by the way):

[
    {
        "pk": "4b678b301dfd8a4e0dad910de3ae245b",
        "model": "sessions.session",
        "fields": {
            "expire_date": "2013-01-16T08:16:59.844Z",
            ...
        }
    }
]

You can also see in deserialize 's doc that this function returns an iterator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM