[英]How to read json file and populate variables with the content using Class
我正在尝试编写一个 class ,它将在构造函数中获取一个字符串变量并将验证文件路径,如果有效将加载文件并使用内容填充变量以及 class 为每个变量设置吸气剂。
这是 json 文件:
{
"name": [
"Caadi",
"Iskadhig"
],
"location": 20356,
"job": "Engineer",
"address": [
{
"city": "Swindon",
"county": [
"Avon"
]
}
]
}
到目前为止,我已经尝试过以下代码:
import json
import os.path
class Config:
def __init__(self, file_name,name,location,job,address):
self.file_name = file_name
self.name = name
self.location = location
self.job = job
self.address = address
try:
if os.path.exists(
'/CaseConfig.json'): # validate the file path
with open('/CaseConfig.json', 'r') as file:
json_file_data = file.read() # read the content of file
self.file_name.get_json_content_file = json.loads(json_file_data) # the content of file
else:
print("File doesn't exist please check the path")
except Exception as e:
print("File not accessible", e)
def getName(self):
return self.name
def getLocation(self):
return self.location
def getJob(self):
return self.job
def getAddress(self):
return self.address
obj = Config('file_name', 'name', 'location', 'job', 'address')
我被卡住了,不确定为什么会出现以下错误:
File not accessible 'str' object has no attribute 'get_json_content_file'
您的 JSON 文件有新行,您必须删除它们。 尝试以下操作:
json_file_data = file.read().replace("\n","")
如果您读取文件file.read()
它至少在这种情况下会被转换为字符串。 为了正确读取 JSON 文件,您想做这样的事情
with open("your file nane.json", "r") as file:
data = json.load(file)
在您的情况下,数据将是
{'name': ['Caadi', 'Iskadhig'], 'location': 20356, 'job': 'Engineer', 'address': [{'city': 'Swindon', 'county': ['Avon']}]}
您可以像其他任何方式一样从该字典中读取数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.