Skip to content

Commit e95b850

Browse files
committed
split apart json.loads and json.load functions in lesson. Co-author @lasse-cs
1 parent 1150538 commit e95b850

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

episodes/02-dictionaries.md

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -345,20 +345,26 @@ True
345345
## JSON files
346346

347347
Because JSON files are such a widely used format, python has a built in package for working with JSON, called `json`:
348+
This package provides the method `json.load()` to read JSON data from a file and and convert it to a python dictionary:
348349

349350
```python
350351
import json
351-
import glob
352352

353-
filenames = sorted(glob.glob('*.json'))
353+
with open('ro-crate-metadata-1.json') as f:
354+
data = json.load(f)
355+
```
356+
357+
The closely related method `json.loads()` (s for "string") reads a string containing JSON and turns it into a Python dictionary:
354358

355-
j_objects = {}
356-
for filename in filenames:
357-
with open(filename) as f:
358-
j_objects[filename] = json.loads(f.read())
359+
```python
360+
json_string = '{"numbers": [1, 2, 3]}'
361+
d = json.loads(json_string)
362+
d['numbers']
359363
```
360364

361-
The `f.read` method reads the file as a single string, which the `json.loads()` method then turns into a dictionary, following the JSON standard.
365+
```output
366+
[1, 2, 3]
367+
```
362368

363369
## HTTP requests
364370

0 commit comments

Comments
 (0)