如何将JSON框架列表转换为JSON框架

问题描述:

我要转换JSON对象列表或单个JSON框架

I want to convert List of JSON object ot Single JSON frame

这是我的代码

for i in user1:
    name=i.name
    password=i.password
    id1=i.id
    user = { "name" : name,
              "password" : password,
              "id":id1}
    user = json.dumps(user)
    userid.append(user)

我得到的输出是

['{"password":"A123","name":"Sam","id":1}','{"password": "B123",名称":"Sammy","id":2}','{密码":"C123",名称": "Abhi","id":3}']

['{"password": "A123", "name": "Sam", "id": 1}', '{"password": "B123", "name": "Sammy", "id": 2}', '{"password": "C123", "name": "Abhi", "id": 3}']

我想要的是

{{"password":"A123","name":"Sam","id":1},{"password": "B123","name":"Sammy","id":2},{"password":"C123","name": "Abhi","id":3}}

{{"password": "A123", "name": "Sam", "id": 1},{"password": "B123", "name": "Sammy", "id": 2},{"password": "C123", "name": "Abhi", "id": 3}}

json.dumps()返回一个字符串,因此您将字符串追加到userid -因此最终显示了字符串列表.

json.dumps() returns a string, so you're append strings to userid—and thus end up with the list of strings shown.

如果您想要使用id作为主键的字典词典,则只需:

If you want a dictionary of dictionaries using the id as the primary key, all you need is:

users = {i.id: {"name": i.name, "password": i.password} for i in user1}