简体   繁体   中英

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.

Here is the json file:

{
  "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. 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. in order to properly read a JSON file you want to do something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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