Last Updated : 23 Aug, 2023
JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate.
Python Format JSONJavascript Object Notation abbreviated as JSON is a lightweight data interchange format. It encodes Python objects as JSON strings and decodes JSON strings into Python objects.
The conversions are based on this conversion table.
Python JSON encodingThe JSON module provides the following two methods to encode Python objects into JSON format. We will be using dump(), dumps(), and JSON.Encoder class. The json.dump() method is used to write Python serialized objects as JSON formatted data into a file. The JSON. dumps() method encodes any Python object into JSON formatted String.
Python3
from io import StringIO
import json
fileObj = StringIO()
json.dump(["Hello", "Geeks"], fileObj)
print("Using json.dump(): "+str(fileObj.getvalue()))
class TypeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, type):
return str(obj)
print("Using json.dumps(): "+str(json.dumps(type(str), cls=TypeEncoder)))
print("Using json.JSONEncoder().encode" +
str(TypeEncoder().encode(type(list))))
print("Using json.JSONEncoder().iterencode" +
str(list(TypeEncoder().iterencode(type(dict)))))
Output:
Using json.dump(): ["Hello", "Geeks"] Using json.dumps(): "" Using json.JSONEncoder().encode"" Using json.JSONEncoder().iterencode['""']Decode JSON in Python
JSON string decoding is done with the help of the inbuilt method json.loads() & json.load() of JSON library in Python. The json.loads() is used to convert the JSON String document into the Python dictionary, and The json.load() is used to read the JSON document from the file.
Python3
from io import StringIO
import json
fileObj = StringIO('["Geeks for Geeks"]')
print("Using json.load(): "+str(json.load(fileObj)))
print("Using json.loads(): "+str(json.loads
('{"Geeks": 1, "for": 2, "Geeks": 3}')))
print("Using json.JSONDecoder().decode(): " +
str(json.JSONDecoder().decode
('{"Geeks": 1, "for": 2, "Geeks": 3}')))
print("Using json.JSONDecoder().raw_decode(): " +
str(json.JSONDecoder().raw_decode('{"Geeks": 1,
"for": 2, "Geeks": 3}')))
Output:
Using json.load(): ['Geeks for Geeks'] Using json.loads(): {'for': 2, 'Geeks': 3} Using json.JSONDecoder().decode(): {'for': 2, 'Geeks': 3} Using json.JSONDecoder().raw_decode(): ({'for': 2, 'Geeks': 3}, 34)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4