【问题标题】:Simplejson dump and load not returning valid dictionarySimplejson 转储和加载未返回有效字典
【发布时间】:2011-01-03 07:06:26
【问题描述】:

我正在尝试将 json 结果存储在 GAE 数据存储中,以便稍后阅读。我将它转储到一个字符串,然后存储它,然后读取它并将其加载回一个字典。但加载后我无法再将其作为字典阅读。

result = freebase.mqlready(query)

打印结果:

[{u'mid': u'/m/095hd',
  u'name': u'Settlers of Catan',
  u'type': u'/games/game'},
 {u'mid': u'/m/025sm93',
  u'name': u'The Game of Life',
  u'type': u'/games/game'}]

 

for r in result:
    name = r.name # works, I can get the name and other values.

json_dump = simplejson.dumps(result)
text = db.Text(json_dump)
fbresult = model.FB(text=text)
fbresult.put()
####
stored_text = fbresult.text
json = simplejson.loads(stored_text)

打印json:

[{u'mid': u'/m/095hd',
  u'name': u'Settlers of Catan',
  u'type': u'/games/game'},
 {u'mid': u'/m/025sm93',
  u'name': u'The Game of Life',
  u'type': u'/games/game'}]

 

for j in json:
    name = json.name 

错误:

AttributeError: 'dict' object has no attribute 'name'

【问题讨论】:

  • 你的变量名json与模块名json冲突

标签: python json google-app-engine simplejson


【解决方案1】:

呃,看起来您正在访问集合而不是内部对象:

你的意思是:

for j in json:
    name = j['name']

【讨论】:

    【解决方案2】:

    Ordinary dictionary 不会将属性访问转换为项目查找:

    >>> d = {'name': 'Joe'}
    >>> d.name
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    AttributeError: 'dict' object has no attribute 'name'
    >>> d['name']
    'Joe'
    

    simplejson默认返回普通字典。

    您可以使用Storage 对象,它类似于字典,但可以使用obj.foo 除了obj['foo']。

    >>> from storage import Storage
    >>> s = Storage(d)
    >>> s['name']
    'Joe'
    >>> s.name
    'Joe'
    

    您可以使用 object_hook 参数将所有 json 对象转换为 Storage:

    obj = simplejson.loads(stored_text, object_hook=Storage)
    

    【讨论】:

      【解决方案3】:

      似乎 freebase.mqlready 返回的result 不是真正的字典,而是通过__getattr__ 委托给__getitem__ 的子类(即:您可以使用r.name 而不是r['name'])。 simplejson 可以很好地转储它(它是一个 dict 子类),但是当它重新加载它时,它会返回一个普通的 dict 而不是将属性访问委托给项目访问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-05
        相关资源
        最近更新 更多