Django反序列化错误:字符串索引必须是整数

时间:2014-03-15 07:55:23

标签: python json django rest serialization

我是json,Python和Django的新手。我在网上做了一些研究但没有解决我的问题。提前感谢任何见解!

我正在构建一个允许移动设备更新服务器数据库的系统,该数据库由Django管理。我目前只在我的本地机器上测试,我向Django识别的URL发送请求。

第一步我有一段试图与服务器通信的python代码。

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

然后在服务器上调用view函数。

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

我收到的错误信息是:

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

1 个答案:

答案 0 :(得分:3)

example JSON file Django的文档中所示(实际上是我检查过的最后一个地方),deserialize列出了一个字典列表(应该有{顺便说一下,{1}}键:

fields

您还可以在deserialize's doc中看到此函数返回迭代器。