I want to have simple data structure, and save it to disk as json, and later take the json and put back into the data structure.
This is the error I get:
AttributeError: ‘dict’ object has no attribute ‘saveToFile’
with the code below:
import json
from typing_extensions import TypedDict
class AutoBlog(TypedDict):
blog_title: str
blog_prompt: str
min_words: int
max_words: int
def saveToFile(self, filename):
str_json = json.dumps(self)
with open(filename, 'w', encoding='unicode-escape') as f:
f.write(str_json)
def readFromFile(self, filename):
with open(filename) as f:
str_json = f.read()
self = json.loads(str_json)
if __name__ == "__main__":
filename = 'c:/Users/All Users/WebsiteGarden/test_serialize.json'
print("Filename=" + filename)
autoBlogData1 = AutoBlog()
autoBlogData1['blog_title'] = "my blog title"
autoBlogData1['blog_prompt'] = "write an article about xyz"
autoBlogData1['min_words'] = 800
autoBlogData1['max_words'] = 1200
autoBlogData1.saveToFile(filename)
autoBlogData2 = AutoBlog()
autoBlogData2.readFromFile(filename)
print("autoBlogData2['blog_title']=" + autoBlogData2['blog_title'])