Python:JSON: Difference between revisions

From wiki
Jump to navigation Jump to search
Created page with ";import json :Enable json functions ;json.dumps(dict, indent=4) :Return the dict nicely structured. Indent each level with 4 spaces. :Can be used on other datatypes too."
 
No edit summary
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
;import json
[[Category:Python]]
:Enable json functions
;import [https://docs.python.org/3/library/json.html json]
:Enable json functions. The json module is standard available (no installation needed)


;json.loads(<jsonstring>)
:Return <jsonstring> as [[Python:DataTypes#Dictionary_or_dict|dict]].
;json.load(<fh>)
:Read a jsonstring from the file opened on <fh> and return it as [[Python:DataTypes#Dictionary_or_dict|dict]].
<syntaxhighlight lang=python>
import json
with open(filename) as fh:
    data = json.load(fh)
</syntaxhighlight>
:Read a jsonstring from an url into a [[Python:DataTypes#Dictionary_or_dict|dictionary]].
<syntaxhighlight lang=python>
import json
import requests
response = json.loads(requests.get(url).text)
for key in response:
    print(key)
</syntaxhighlight>
Below 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)
:Return the dict nicely structured. Indent each level with 4 spaces.
:Convert a dict into a json string nicely formatted. Indent each level with 4 spaces.
:Can be used on other datatypes too.
;json.dump(dict, fh, indent=4)
:Dumps to the [[Python:Files|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 (",", ": ")
 
Not all objecttypes can be dumps by json e.g. Decimals and datetime objects. I found this on stackexchange[https://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object]
If you want to dump the exact value return as string, else as float.
<syntaxhighlight lang=python>
 
class DecimalEncoder(json.JSONEncoder):
    ''' To make Decimals json dumpable
    json.dumps({<object to dump>, cls=DecimalEncoder)'
    '''
    import json
    import decimal
    from datetime import datetime
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            #return (str(o))
            return (float(o))
        elif isinstance(o, datetime):
            return (str(o))
        return super(DecimalEncoder, self).default(o)
</syntaxhighlight>

Latest revision as of 11:58, 27 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 (",", ": ")

Not all objecttypes can be dumps by json e.g. Decimals and datetime objects. I found this on stackexchange[1]

If you want to dump the exact value return as string, else as float.

class DecimalEncoder(json.JSONEncoder):
    ''' To make Decimals json dumpable
    json.dumps({<object to dump>, cls=DecimalEncoder)'
    '''
    import json
    import decimal
    from datetime import datetime
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            #return (str(o))
            return (float(o))
        elif isinstance(o, datetime):
            return (str(o))
        return super(DecimalEncoder, self).default(o)