Difference between revisions of "Python:JSON"

From wiki
Jump to navigation Jump to search
m
 
(2 intermediate revisions by the same user not shown)
Line 3: Line 3:
 
:Enable json functions. The json module is standard available (no installation needed)
 
:Enable json functions. The json module is standard available (no installation needed)
  
;json.load(<data>)
+
;json.loads(<jsonstring>)
:Return <data> as [[Python:DataTypes#Dictionary_or_dict|dict]].
+
: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>
 
<syntaxhighlight lang=python>
 
import json
 
import json
Line 10: Line 12:
 
     data = json.load(fh)
 
     data = json.load(fh)
 
</syntaxhighlight>
 
</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.
 
Below can be used on [[Python:DataTypes|datatypes]] like lists and tuples too, not on sets.

Latest revision as of 16:27, 18 October 2021

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.