Skip to content

Commit 2e2d70c

Browse files
committed
Add info on working with file objects
1 parent ecc570d commit 2e2d70c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

docs/scenarios/json.rst

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,36 @@ You can also convert the following to JSON:
3939
print(json.dumps(d))
4040
'{"first_name": "Guido", "last_name": "Rossum", "titles": ["BDFL", "Developer"]}'
4141
42+
Working with File Objects
43+
-------------------------
44+
45+
We can also load a JSON file by using ``json.load`` instead of ``json.loads``:
46+
47+
.. code-block:: python
48+
49+
import json
50+
51+
with file('path/to/file.json') as f:
52+
loaded_json = json.load(f)
53+
54+
print(loaded_json) # {'first_name': 'Ada', 'last_name': 'Lovelace'}
55+
56+
Here's an example of writing directly to a file by using ``json.dump`` instead of ``json.dumps``:
57+
58+
.. code-block:: python
59+
60+
import json
61+
62+
my_data = {
63+
'name': 'Alan Turing',
64+
'played_by': 'Benedict Cumberbatch'
65+
}
66+
67+
with file('path/to/file.json', 'w') as f:
68+
json.dump(my_data, f)
69+
70+
``path/to/file.json`` now contains a JSON representation of the my_data dictionary.
71+
4272

4373
simplejson
4474
----------

0 commit comments

Comments
 (0)