如何反序列化此JSON对象?

时间:2011-03-08 06:46:51

标签: python django json deserialization

import simplejson
from urllib2 import urlopen
from simplejson import loads
from django.core import serializers
content = loads(urlopen('https://graph.facebook.com/1234676502/feed').read())
content =  simplejson.dumps(content,sort_keys=True, indent=4)
print content
json_serializer = serializers.get_serializer("json")()
json_serializer.deserialize(content)

运行上面的python代码时遇到以下错误:

Traceback (most recent call last):
  File "/var/www/youedo/test.py", line 22, in <module>
    json_serializer = serializers.get_serializer("json")()
  File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 63, in get_serializer
    _load_serializers()
  File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 109, in _load_serializers
    register_serializer(format, BUILTIN_SERIALIZERS[format], serializers)
  File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 51, in register_serializer
    module = importlib.import_module(serializer_module)
  File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/xml_serializer.py", line 6, in <module>
    from django.core.serializers import base
  File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/base.py", line 7, in <module>
    from django.db import models
  File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 14, in <module>
    if not settings.DATABASES:
  File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__
    self._setup()
  File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 38, in _setup
    raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

...当我打印内容时,它会正确打印JSON字符串。

修改:2     import simplejson     来自urllib2 import urlopen     来自simplejson导入负载     来自django.core导入序列化程序     content = loads(urlopen('https://graph.facebook.com/1234676502/feed')。read())

json_serializer = serializers.get_serializer("json")()
json_serializer.get_deserialize(content)

我把这段代码放在我的view.py中然后我收到了以下错误:

AttributeError at /rss

'Serializer' object has no attribute 'get_deserialize'

Request Method:     GET
Request URL:    http://127.0.0.1:8000/rss
Django Version:     1.2.4
Exception Type:     AttributeError
Exception Value:    

'Serializer' object has no attribute 'get_deserialize'

1 个答案:

答案 0 :(得分:1)

您的错误与json本身无关,它明确指出它无法导入DJANGO_SETTINGS,这意味着您没有django应用程序上下文。最简单的方法是安装django extensions,它提供了命令./manage.py runscript,它使用你的django应用程序上下文来运行你的脚本。

Django extensions can be found here

修改:查看第二次修改,我发现您使用的是方法get_deserialize(),正确的方法应该是deserialize(),AFAIK。