Python:JSON: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
No edit summary |
||
| Line 31: | Line 31: | ||
;json.dump(dict, fh, indent=4) | ;json.dump(dict, fh, indent=4) | ||
:Dumps to the [[Python:Files|file opened]] on filehandle fh. | :Dumps to the [[Python:Files|file opened]] on filehandle fh. | ||
;json.dumps(list(set), indent='text ', separators=( | ;json.dumps(list(set), indent='text ', separators=("",""), sort_keys=True) | ||
:list set per line with 'text ' prepended and no separators. | :list set per line with 'text ' prepended and no separators. Seperators is a tuple (line-separator, key-value-separator), default is (",", ": ") | ||
Revision as of 19:12, 14 January 2025
- import json
- Enable json functions. The json module is standard available (no installation needed)
- json.loads(<jsonstring>)
- Return <jsonstring> as dict.
- json.load(<fh>)
- Read a jsonstring from the file opened on <fh> and return it as dict.
import json
with open(filename) as fh:
data = json.load(fh)
- Read a jsonstring from an url into a dictionary.
import json
import requests
response = json.loads(requests.get(url).text)
for key in response:
print(key)
Below can be used on datatypes like lists and tuples too, not on sets.
- json.dumps(dict, indent=4)
- Convert a dict into a json string nicely formatted. Indent each level with 4 spaces.
- json.dump(dict, fh, indent=4)
- Dumps to the file opened on filehandle fh.
- json.dumps(list(set), indent='text ', separators=("",""), sort_keys=True)
- list set per line with 'text ' prepended and no separators. Seperators is a tuple (line-separator, key-value-separator), default is (",", ": ")