如何使用python从json获取精确数据

问题描述 投票:-1回答:2

我试图解析json文件时遇到错误

{
0:
    {
        'data':
            [
                {
                    'state': 1,
                    'invitation_sent_at': None,
                    'group_id': None,
                    'firstname': 'goog',
                    'company': 'wbru',
                    'member_of': None,
                    'updated_at': '2017-07-21T08:07:45.375Z',
                    'last_login': None,
                    'manager_ad_id': None,
                    'distinguished_name': None,
                    'comment': '',
                    'username': 'predicted',
                    'title': '',
                    'lastname': 'hello',
                    'samaccountname': None,
                    'status': 1,
                    'locked_until': None,
                    'locale_code': None,
                    'role_id': None,
                    'userprincipalname': None,
                    'phone': '777',
                    'openid_name': 'gege',
                    'directory_id': None,
                    'id': 34486990,
                    'department': '',
                    'activated_at': None,
                    'external_id': None,
                    'created_at': '2017-07-21T08:07:45.347Z',
                    'email': '[email protected]',
                    'password_changed_at': None,
                    'invalid_login_attempts': None
                },
            ], 
        'pagination':
            {
                'before_cursor': None,
                'previous_link': None,
                'after_cursor': None,
                'next_link': None
            },
       'status':
            {
                'type': 'success',
                'message': 'Success',
                'code': 200,
                'error': False
            }
    }
}

所以我需要得到身份证明。我用了

dumps = json.dumps(allUsers)
print(dumps)

这将打印出json文件。但是当我试图获取数据或id时,它会显示此错误

print(dumps['data'])

Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: string indices must be integers

拜托,帮我搞个名。

python json
2个回答
1
投票
print(json.loads(dumps)[“data”][0]['id')

json.loads()接受一个json字符串。然后根据你的json将它转换成python dict或python list。在这种情况下,它将其转换为dict

一旦有了dict,就可以使用["data"]访问属性。

如果你遇到TypeError: string indices must be integers错误,这意味着json.loads(dumps)可能会返回listdict,而不是dict。所以你可能需要做以下事情。

print(json.loads(dumps)[0]["data"][0]["id"]

[0]将选择列表中的第一个对象,然后您可以访问其数据属性。

希望有道理!


0
投票

dumps是一个字符串而不是字典,所以你不能访问'data'

© www.soinside.com 2019 - 2024. All rights reserved.