diff --git a/src/intermediate/json_csv/json_file.py b/src/intermediate/json_csv/json_file.py new file mode 100644 index 0000000..7c9a039 --- /dev/null +++ b/src/intermediate/json_csv/json_file.py @@ -0,0 +1,50 @@ + + +import json +import os + + +def read_json(): + json_string = '{"name": "Anikuttan", "age": 25}' + + data = json.loads(json_string) + print(data) # {'name': 'Anikuttan', 'age': 25} + print(data["age"]) # 25 + + +def save_person_json(): + my_json = { + "first_name": "Anikuttan", + "last_name": "Vijayakumar", + "phone_number": 9092325424, + "skills": ["Python", "Dart", "Flutter"], + "extra": None, + "married": False, + } + + json_string = json.dumps(my_json) # json.dumps gives the string + print(json_string) + + # get the folder where this script is located + current_dir = os.path.dirname(os.path.abspath(__file__)) + file_path = os.path.join(current_dir, "person.json") + + # with open(file_path, 'w') as file: + # file.write(json_string) + with open(file_path, "w") as file: + # json.dump is used to write JSON data directly into a file. + json.dump(my_json, file, indent=4) + + +def read_json_from_file(): + + current_dir = os.path.dirname(os.path.abspath(__file__)) + file_path = os.path.join(current_dir, "person.json") + with open(file_path, "r") as file: + print(json.load(file)) + + +if __name__ == "__main__": + save_person_json() + read_json() + read_json_from_file() diff --git a/src/intermediate/json_csv/person.json b/src/intermediate/json_csv/person.json new file mode 100644 index 0000000..b73975b --- /dev/null +++ b/src/intermediate/json_csv/person.json @@ -0,0 +1,8 @@ +{ + "first_name": "Anikuttan", + "last_name": "Vijayakumar", + "phone_number": 9092325424, + "skills": ["Python", "Dart", "Flutter"], + "extra": null, + "married": false +}