Skip to content

Commit 72909dc

Browse files
committed
JSON MDODULE load loads dump dumps update and append
1 parent 406004d commit 72909dc

File tree

2 files changed

+295
-0
lines changed

2 files changed

+295
-0
lines changed

contrib/advanced-python/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
# List of sections
22

33
- [Decorators/\*args/**kwargs](decorator-kwargs-args.md)
4+
- [JSON module](json-module.md)
Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
# JSON Module
2+
3+
## What is JSON?
4+
5+
- <a href="https://www.json.org/json-en.html">JSON (JavaScript Object Notation)</a> is a format for structuring data.
6+
- JSON is a lightweight, text-based data interchange format that is completely language-independent.
7+
- Similar to XML, JSON is a format for structuring data commonly used by web applications to communicate with each other.
8+
9+
## Why JSON?
10+
11+
- Whenever we declare a variable and assign a value to it, the variable itself doesn't hold the value. Instead, the variable holds an address in memory where the value is stored. For example:
12+
13+
```python
14+
age = 21
15+
```
16+
17+
- When we use `age`, it gets replaced with `21`. However, <i>age doesn't contain 21, it contains the address of the memory location where 21 is stored</i>.
18+
19+
- While this works locally, transferring this data, such as through an API, poses a challenge. Sending your computer’s entire memory with the addresses is impractical and insecure. This is where JSON comes to the rescue.
20+
21+
### Example JSON
22+
23+
- JSON supports most widely used data types including String
24+
, Number, Boolean, Null, Array and Object.
25+
- Here is an example of JSON file
26+
27+
```json
28+
{
29+
"name": "John Doe",
30+
"age": 21,
31+
"isStudent": true,
32+
"address": null,
33+
"courses": ["Math", "Science", "History"],
34+
"grades": {
35+
"Math": 95,
36+
"Science": 89,
37+
"History": 76
38+
}
39+
}
40+
```
41+
42+
# Python JSON
43+
44+
Python too supports JSON with a built-in package called `json`. This package provides all the necessary tools for working with JSON Objects including `parsing, serializing, deserializing, and many more`.
45+
46+
## 1. Python parse JSON string.
47+
48+
- To parse JSON string Python firstly we import the JSON module.
49+
- JSON string is converted to a Python object using `json.loads()` method of JSON module in Python.
50+
- Example Code:
51+
52+
```python
53+
# Python program to convert JSON to Python
54+
import json
55+
56+
# JSON string
57+
students ='{"id":"01", "name": "Yatharth", "department":"Computer Science Engineering"}'
58+
59+
# Convert string to Python dict
60+
students_dict = json.loads(students)
61+
print(students_dict)
62+
63+
print(students_dict['name'])
64+
65+
```
66+
67+
- Ouput:
68+
69+
```json
70+
{'id': '01', 'name': 'Yatharth', 'department': 'Computer Science Engineering'}
71+
Yatharth
72+
```
73+
74+
## 2. Python load JSON file.
75+
76+
- JSON data can also be directly fetch from a json file
77+
- Example:
78+
79+
```python
80+
import json
81+
# Opening JSON file
82+
f = open('input.json',)
83+
84+
# Returns JSON object as a dictionary
85+
data = json.load(f)
86+
87+
# Iterating through the json file
88+
for i in data['students']:
89+
print(i)
90+
91+
# Closing file
92+
f.close()
93+
```
94+
95+
- JSON file
96+
97+
```json
98+
{
99+
"students":{
100+
{
101+
"id": "01",
102+
"name": "Yatharth",
103+
"department": "Computer Science Engineering"
104+
},
105+
{
106+
"id": "02",
107+
"name": "Raj",
108+
"department": "Mechanical Engineering"
109+
}
110+
}
111+
}
112+
```
113+
114+
- Ouput
115+
116+
```json
117+
{'id': '01', 'name': 'Yatharth', 'department': 'Computer Science Engineering'}
118+
{'id': '02', 'name': 'Raj', 'department': 'Mechanical Engineering'}
119+
```
120+
- `json.load()`: Reads JSON data from a file object and deserializes it into a Python object.
121+
- `json.loads()`: Deserializes JSON data from a string into a Python object.
122+
<hr>
123+
124+
### Addtiotnal Context
125+
Relation between python data types and json data types is given in table below.
126+
</br>
127+
128+
| Python Object | JSON Object |
129+
|-----------------|-------------|
130+
| Dict | object |
131+
| list, tuple | array |
132+
| str | string |
133+
| int, long, float | numbers |
134+
| True | true |
135+
| False | false |
136+
| None | null |
137+
138+
139+
140+
## 3. Python Dictionary to JSON String
141+
- Parsing python dictionary to json string using `json.dumps()`.
142+
- Example Code:
143+
```python
144+
import json
145+
146+
# Data to be written
147+
dictionary ={
148+
"id": "03",
149+
"name": "Suraj",
150+
"department": "Civil Engineering"
151+
}
152+
153+
# Serializing json
154+
json_object = json.dumps(dictionary, indent = 4)
155+
print(json_object)
156+
```
157+
- Output:
158+
``` json
159+
{
160+
"department": "Civil Engineering",
161+
"id": "02",
162+
"name": "Suraj"
163+
}
164+
```
165+
## 4. Python Dictionary to JSON file.
166+
- - Parsing python dictionary to json string using `json.dump()`.
167+
- Example Code:
168+
``` python
169+
import json
170+
171+
# Data to be written
172+
dictionary ={
173+
"name" : "Satyendra",
174+
"rollno" : 51,
175+
"cgpa" : 8.8,
176+
"phonenumber" : "123456789"
177+
}
178+
179+
with open("sample.json", "w") as outfile:
180+
json.dump(dictionary, outfile)
181+
182+
```
183+
- Ouput: `sample.json`
184+
``` json
185+
{
186+
"name" : "Satyendra",
187+
"rollno" : 51,
188+
"cgpa" : 8.8,
189+
"phonenumber" : "123456789"
190+
}
191+
192+
```
193+
## 5. Append Python Dictionary to JSON String.
194+
- Append to an already existing string using `json.update()`.
195+
- Example :
196+
```python
197+
import json
198+
# JSON data:
199+
x = {
200+
"id": "03",
201+
"name": "Suraj"
202+
}
203+
204+
# python object to be appended
205+
y = { "department": "Civil Engineering"}
206+
207+
# parsing JSON string:
208+
z = json.loads(x)
209+
210+
# appending the data
211+
z.update(y)
212+
213+
# the result is a JSON string:
214+
print(json.dumps(z))
215+
216+
```
217+
- Ouput:
218+
```json
219+
{"id": "03", "name": "Suraj", "department": "Civil Engineering"}
220+
```
221+
222+
223+
## 6. Append Python Dictionary to JSON File.
224+
- There is no direct function to append in file. So, we will load file in a dictionary, update dictionary then update content and convert back to json file format.
225+
- `data.json`
226+
``` json
227+
{
228+
"students":{
229+
{
230+
"id": "01",
231+
"name": "Yatharth",
232+
"department": "Computer Science Engineering"
233+
},
234+
{
235+
"id": "02",
236+
"name": "Raj",
237+
"department": "Mechanical Engineering"
238+
}
239+
}
240+
}
241+
```
242+
- Example Code:
243+
``` python
244+
import json
245+
246+
# function to add to JSON
247+
def write_json(new_data, filename='data.json'):
248+
with open(filename,'r+') as file:
249+
# First we load existing data into a dict.
250+
file_data = json.load(file)
251+
# Join new_data with file_data inside students
252+
file_data["students"].append(new_data)
253+
# Sets file's current position at offset.
254+
file.seek(0)
255+
# convert back to json.
256+
json.dump(file_data, file, indent = 4)
257+
258+
# python object to be appended
259+
y = {
260+
"id": "03",
261+
"name": "Suraj",
262+
"department": "Civil Engineering"
263+
}
264+
265+
write_json(y)
266+
267+
```
268+
- Output:
269+
```json
270+
{
271+
"students":{
272+
{
273+
"id": "01",
274+
"name": "Yatharth",
275+
"department": "Computer Science Engineering"
276+
},
277+
{
278+
"id": "02",
279+
"name": "Raj",
280+
"department": "Mechanical Engineering"
281+
},
282+
{
283+
"id": "03",
284+
"name": "Suraj",
285+
"department": "Civil Engineering"
286+
}
287+
}
288+
}
289+
```
290+
291+
</br>
292+
<hr>
293+
294+
The Python json module simplifies the handling of JSON data, offering a bridge between Python data structures and JSON representations, vital for data exchange and storage in modern applications.

0 commit comments

Comments
 (0)