Python:JSON: Difference between revisions

From wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 10: Line 10:
</syntaxhighlight>
</syntaxhighlight>


Can be used on [[Python:DataTypes|datatypes]] like lists and tuples too, not on sets.
;json.dumps(dict, indent=4)
;json.dumps(dict, indent=4)
:Convert a dict into a json string nicely structured. Indent each level with 4 spaces.
:Convert a dict into a json string nicely structured. Indent each level with 4 spaces.
:Can be used on other [[Python:DataTypes|datatypes]] too.
;json.dump(dict, fh, indent=4)
:Dumps to the [[Python:Files|file opened]] on filehandle fh.

Revision as of 08:42, 5 May 2019

import json
Enable json functions. The json module is standard available (no installation needed)

Read a json file and return it as dict.

import json
with open(filename) as fh:
    data = json.load(fh)

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 structured. Indent each level with 4 spaces.
json.dump(dict, fh, indent=4)
Dumps to the file opened on filehandle fh.