json file operations

This commit is contained in:
2025-08-24 19:15:42 +05:30
parent 26153becb1
commit 0dcec244bc
2 changed files with 58 additions and 0 deletions

View File

@@ -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()

View File

@@ -0,0 +1,8 @@
{
"first_name": "Anikuttan",
"last_name": "Vijayakumar",
"phone_number": 9092325424,
"skills": ["Python", "Dart", "Flutter"],
"extra": null,
"married": false
}