Skip to content

Commit 57b212b

Browse files
committed
json dumps with encode method
1 parent 93f9a38 commit 57b212b

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

network-programming.md

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,40 @@
11
# Network Programming
22

33
## JSON
4+
### loads
45
To parse a JSON string into a Python object, use the `json.loads()` method from the `json` module.
56
```python
67
import json
78
customer_info = '{"name": "Craig", "age": 41, "city": "Rockingham"}'
89
customer = json.loads(customer_info)
910
```
10-
11+
### dumps
1112
To convert Python data types into JSON data, use the `json.dumps()` method.
1213
```python
1314
import json
1415
club = {"club": "Rangers", "year_founded": 1872, "city": "Glasgow"}
1516
club_info = json.dumps(club)
1617
```
18+
You can't dump the content of an object by default, as the `json` module doesn't know how to convert it to JSON. You need to define a custom method to convert the object to a dictionary or use the `default` parameter of `json.dumps()` to specify a function that converts the object to a JSON-serializable format.
19+
```python
20+
import json
21+
22+
class Competition:
23+
def __init__(self, name, prize_money):
24+
self.name = name
25+
self.prize_money = prize_money
26+
27+
def encode_competition(competition):
28+
if isinstance(competition, Competition):
29+
return competition.__dict__
30+
31+
raise TypeError(f"Object of type {competition.__class__.__name__} is not JSON serializable")
32+
33+
the_open = Competition("The Open Championship", 1860)
34+
print(json.dumps(the_open, default=encode_competition))
35+
# {"name": "The Open Championship", "prize_money": 1860}
36+
```
37+
1738
Python objects converted to their JSON equivalents:
1839

1940
| Python | JSON |

0 commit comments

Comments
 (0)