json file operations
This commit is contained in:
50
src/intermediate/json_csv/json_file.py
Normal file
50
src/intermediate/json_csv/json_file.py
Normal 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()
|
||||||
8
src/intermediate/json_csv/person.json
Normal file
8
src/intermediate/json_csv/person.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"first_name": "Anikuttan",
|
||||||
|
"last_name": "Vijayakumar",
|
||||||
|
"phone_number": 9092325424,
|
||||||
|
"skills": ["Python", "Dart", "Flutter"],
|
||||||
|
"extra": null,
|
||||||
|
"married": false
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user