python - 为 json 中的实例创建对象
问题描述
所以我有一个 JSON 文件
{
"Vehicles": [
{
"Name": "Car",
"ID": 1
},
{
"Name": "Plane",
"ID": 2
}
]
}
我在python中创建了这个类
class vehicleclass:
def __init__(self, vname, vid):
self.name = vname
self.id = vid
我想做的是在 JSON 中为每辆车创建一个对象车辆的实例,我正在从文件中读取,如下所示
with open('vehicle.json') as json_file:
data = json.load(json_file)
然后我运行这段代码
for each in data['Vehicles']:
如何使用 JSON 文件中的每个“名称”迭代创建车辆类的实例
each['Name']
注意我意识到我可以通过调用for 循环来获取每个“名称”的值
解决方案
据我了解,我认为这应该实现它。
with open("vehicle.json") as json_file: # opens your vehicles.json file
# this will load your file object into json module giving you a dictionary if its a valid json
data = json.load(json_file)
# this list comprehension uses data dictionary to generate your vehicleclass instances
vehicle_instances = [
vehicleclass(vehicle["Name"], vehicle["ID"]) for vehicle in data["Vehicles"]
]
推荐阅读
- ios - 如何通过点击笔尖中的按钮来显示警报?
- java - Logback 记录消息两次,无需使用 Spring 设置配置
- javascript - 如何在 GraphQL 突变中使用 FaunaDB 将数组传递给字段
- python - 为什么蟒蛇不再工作了?我怎样才能解决这个问题
- python - CSS 样式未应用于 Gtk 小部件
- javascript - 如何使我的网站与即将到来的 SharedArrayBuffer 跨域隔离更改兼容
- ruby-on-rails - Rails 表单验证不调用方法
- ios - 登录后使用 Apple“缩小”视图登录
- html - 其他用户登录时如何更改部分html页面内容?
- solr - Solr 6 - 使用子查询/连接查询多个子文档