首页 > 解决方案 > 根据项目类型在python中解析json嵌套的dict项目

问题描述

我想仅根据存储在名为 result 的变量中的本地 json 文件中的键“type”中的“Username”值列出“name”键中的值(使用 json.load(input_file)。文件包含我不希望在结果中出现的其他非用户名字典。

   {
        "count": {
            "references": {
                "returned": 10,
                "total": 17933
            }
        },
        "entities": {
            "KF4UXbl": {
                "name": "johndoe123",
                "type": "Username",
            },
            "KeirTr": {
                "name": "#thash123",
                "hits": 141581,
                "type": "Hashtag",
            },
            "SQsD6o": {
                "name": "goodie1234",
                "type": "Username",
                "modified": "2019-04-12T21:02:51.938Z"
            },
            "type:Speech": {
                "name": "Other",
                "type": "MetaType",
            },
            "QXyWAK": {
                "name": "textuser1234",
                "type": "Username",
            },
            "type:Topic": {
                "name": "Topic",
                "type": "MetaType",
            },
            "KeTJkZ": {
                "name": "TestOrg",
                "type": "Organization",
                "meta_type": "type:Organization",
            },
}

代码

for i, j in result.iteritems():
 if j.get('type') == 'Username':
  print j.get('name')

但是我收到此错误:

    if j.get('type') == 'Username':
AttributeError: 'list' object has no attribute 'get'

如何根据用户名的值打印以下内容?

johndoe123
goodie1234
textuser1234

标签: pythonjsonparsingdictionary

解决方案


推荐阅读