Python json.loads()返回列表而不是dict

fjnneemd  于 2023-01-10  发布在  Python
关注(0)|答案(2)|浏览(357)

我从一个API中得到了下面的json,我是通过requests.get()得到的。现在我想用json.loads()把这个json变成一个dict,但是结果是一个列表。从https://www.w3schools.com/python/python_json.asp开始,结果应该是一个dict ......或者我错了?谢谢!

import requests
    import json

    r = requests.get('http://url/api,                  
    auth=requests.auth.HTTPBasicAuth('user','pass'))

    x = json.loads(r.text)

    # type(x) >>> <class 'list'>

json:
[
    {
        "id": 400285,
        "statusId": 1,
        "deliveryAddress": {
            "firstName": "Admin",
            "lastName": "Admin",
            "company": "Testshop 2",
            "street": "Teststr. 1",
            "houseNumber": "",
            "additionalAddressInfo": "",
            "postcode": "12345",
            "city": "Testort",
            "state": "Bremen",
            "country": "Germany",
            "countryIsoCode": "DE"
        },
        "billingAddress": {
            "firstName": "Admin",
            "lastName": "Admin", 
        }
    },
    {
        "id": 400288,
        "statusId": 1,
        "deliveryAddress": {
            "firstName": "Carolin",
            "lastName": "Pr\u00f6ger",
            "company": "",
            "street": "teststra\u00dfe 12",
            "houseNumber": "",
            "additionalAddressInfo": "",
            "postcode": "12345",
            "city": "Bremen",
            "state": "Bremen",
            "country": "Germany",
            "countryIsoCode": "DE"
        },
        "billingAddress": {
            "firstName": "Carolin",
            "lastName": "Pr\u00f6ger",
        }
    }
]

编辑1:

mydict= {}

for item in mylist:
    mydict['ID'] = item['id']
    mydict['statusID'] = item['statusId']
hvvq6cgz

hvvq6cgz1#

从json.load返回的数据类型是根据json文件的数据结构来赋值的,你的json文件有[](列表结构),但是你需要你的json文件有{}(列表结构)。

rhfm7lfc

rhfm7lfc2#

这是因为你的json响应包含列表而不是对象。

相关问题