簡體   English   中英

如何讀取 json 文件並使用 Class 使用內容填充變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM