File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff 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
4373simplejson
4474----------
You can’t perform that action at this time.
0 commit comments