简体   繁体   English

如何读取 json 文件并使用 Class 使用内容填充变量

[英]How to read json file and populate variables with the content using Class

I am trying to write a class that will take a string variable in the constructor and will validate the file path and if valid will load the file and populate variables with the content and also the class to have getters for each var.我正在尝试编写一个 class ,它将在构造函数中获取一个字符串变量并将验证文件路径,如果有效将加载文件并使用内容填充变量以及 class 为每个变量设置吸气剂。

Here is the json file:这是 json 文件:

{
  "name": [
    "Caadi",
    "Iskadhig"
  ],
  "location": 20356,
  "job": "Engineer",
  "address": [
    {
      "city": "Swindon",
      "county": [
        "Avon"
      ]
      
    }
  ]
}

I have attempted so far the following code:到目前为止,我已经尝试过以下代码:

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')

I am stuck and not sure why I am getting the following error:我被卡住了,不确定为什么会出现以下错误:

File not accessible 'str' object has no attribute 'get_json_content_file'

Your JSON file has new lines, you must get rid of them.您的 JSON 文件有新行,您必须删除它们。 Try the following:尝试以下操作:

json_file_data = file.read().replace("\n","")

if you read a file file.read() it will at least in this casse be converted into a string.如果您读取文件file.read()它至少在这种情况下会被转换为字符串。 in order to properly read a JSON file you want to do something like this为了正确读取 JSON 文件,您想做这样的事情

with open("your file nane.json", "r") as file:
     data = json.load(file)

in your case data will be在您的情况下,数据将是

{'name': ['Caadi', 'Iskadhig'], 'location': 20356, 'job': 'Engineer', 'address': [{'city': 'Swindon', 'county': ['Avon']}]}

you can than read the data out of this dictionary in the same way you would any other您可以像其他任何方式一样从该字典中读取数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM