Reputation: 145
I'm writing a code based on json file that allows the user choose the file in the beginning of the program I wrote the following function to read the file,
file_name = input("Which .json file do you want to open? ")
def read_json_file(file_name):
with open(file_name) as json_file:
weather = js.load(json_file)
return weather
Later, I was advised to rewrite the code using class to get better structure. Since I'm not very familiar with it, I got help to rewrite it like this
class Weather_data:
def __init__(self):
self.file_name = input("Which .json file do you want to open? ")
def read_json_file(self):
with open(self.file_name) as json_file:
weather = js.load(json_file)
return weather
But instead of returning the whole file, is there any way i can only return specific parts of the json file? For example
for i in range(len(weather['date'])):
date = weather['value'][i]['date']
value = weather['value'][i]['value']
i.e only these 2 parts, but i want to be able to access those using my defined class!
Thanks in advance!
Upvotes: 0
Views: 401
Reputation: 398
Basically, put the file name input into the init of the class so when you create an instance it asks for the json file and sets it as an attribute of the class instance.
See here https://www.w3schools.com/python/python_classes.asp
example:
class Weather_data:
def __init__(self):
self.file_name = input("Which .json file do you want to open? ")
def read_json_file(self):
with open(self.file_name) as json_file:
weather = js.load(json_file)
return weather
You could also set the weather to be a attribute of the class , i.e self.weather=js.load(json_file)
and then access it with the instance of your class.
EDIT:
Since you edited your question. You can add a new attribute for each of the things you want to access and then access it via the class instance.
def read_json_file(self):
with open(self.file_name) as json_file:
self.weather = js.load(json_file)
self.value=self.weather['value'] #or whatever you want
Then access via:
weather_data=Weather_data() #instance of the class, will prompt for json file
weather_data.read_json_file() #runs the method
print(weather_data.value) #would print it
Upvotes: 1