首页 > 解决方案 > 如何将 JSON 字符串信息保存到一个整体名称中

问题描述

我正在使用结合 JSON 的 Python。

我基本上希望我的 Python 代码打印出字符串的所有信息,例如 print(profile1)

这是 JSON 文件,其中包括 3 个不同的配置文件,拆分为一个字符串。

字符串 1 = Profile1

字符串 2= Profile2

字符串 3= Profile3

[
  {
    "guid": "1f1c4ac7-fc36-4008-935b-d87ffc7d8700",
    "isActive": false,
    "name": {
      "first": "Reid",
      "last": "Warren"
    },
    "email": "reid.warren@undefined.name",
    "phone": "+1 (983) 443-3504",
    "address": "359 Rapelye Street, Holtville, Marshall Islands, 9692"
  },
  {
    "guid": "0a661c22-ce39-40fb-bcb1-742028cc0c9e",
    "isActive": true,
    "name": {
      "first": "Amelia",
      "last": "Wilkinson"
    },
    "email": "amelia.wilkinson@undefined.us",
    "phone": "+1 (831) 563-3240",
    "address": "525 Allen Avenue, Iola, Kentucky, 894"
  },
  {
    "guid": "e23bbe57-7f46-4e03-9f72-0d7499d96153",
    "isActive": false,
    "name": {
      "first": "Shari",
      "last": "Sullivan"
    },
    "email": "shari.sullivan@undefined.ca",
    "phone": "+1 (922) 472-2774",
    "address": "366 Leonora Court, Cecilia, Pennsylvania, 3333"
  }
]

现在,当我说例如 print(Profile1) 时,我希望我的 python 代码打印出所选配置文件的所有信息(第一个。最后一个,电子邮件,电话,地址)

这是我当前的代码,它打印出所有的名字,所以不仅仅是 Profile1

import json

class User:
    def __init__(self, guid, isActive, name, email, phone, address):
        self.guid = guid
        self.isActive = isActive
        self.first_name = name['first']
        self.last_name = name['last']
        self.email = email
        self.phone = phone
        self.address = address

    @classmethod
    def from_json(cls, json_string):
        json_dict = json.loads(json_string)
        return cls(**json_dict)

    def __repr__(self):
        return f' { self.first_name }'



users_list = []
with open('Data1.json', 'r') as json_file:
    user_data = json.loads(json_file.read())
    for u in user_data:
        users_list.append(User(**u))

print(users_list)

我该怎么做?

标签: pythonjsonstringpython-jsons

解决方案


推荐阅读