【问题标题】:Json to list of dictionariesJson 到字典列表
【发布时间】:2015-08-06 19:00:08
【问题描述】:

我有一个字典列表:

arr= [{'comment': u'NoComment',
  'creator': u'',
  'short': u'WQhBxVA',
  'url': u'https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-django/tp-un-raccourcisseur-d-url',
  'visits': 2},
 {'comment': u'NoComment',
  'creator': u'',
  'short': u'xeSkCWB',
  'url': u'https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-django/tp-un-raccourcisseur-d-urlfze',
  'visits': 0}]

要将其传递给 request.session 字段,我想将其转换为 JSON。所以我有arrj = json.dumps(arr)

但是当我反序列化它时,我无法访问字典:

arro = json.loads(arrj)

这是arro的内容:

[{u'comment': u'NoComment',
  u'creator': u'',
  u'short': u'WQhBxVA',
  u'url': u'https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-django/tp-un-raccourcisseur-d-url',
  u'visits': 2},
 {u'comment': u'NoComment',
  u'creator': u'',
  u'short': u'xeSkCWB',
  u'url': u'https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-django/tp-un-raccourcisseur-d-urlfze',
  u'visits': 0}]

由于 u(unicode 标记?),像 arro[0].url 这样的调用会引发 AttributeError: 'dict' object has no attribute 'url'

有没有办法让我获得反序列化字典数组的url 字段?

【问题讨论】:

  • 那是一个字典。您可以通过按键访问它,就像任何字典一样:dict[u'key']
  • 哈哈当然——'非常感谢你这是愚蠢的:)

标签: python arrays json dictionary


【解决方案1】:

这并不是真正的 JSON 问题。字典不会将它们的键作为属性公开。使用索引:

arro[0]['url']

带有纯 ASCII 字符的键会自动解码以匹配 Unicode 键,因此'url'u'url' 都可以使用。

【讨论】:

    【解决方案2】:

    您不能以 dict.key 访问 dict 中的项目,您需要使用下标访问 - dict[key] 。示例 -

    arro[0]['url']
    

    此错误与字符串前面的 u 无关。

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      相关资源
      最近更新 更多