JSON is a syntax for storing and exchanging data. JSON is text, written with JSON. Python has a built-in package called json, which can be used to work with the JSON data.
- Importing json module
- Parse JSON (Convert from JSON to Python object)
If you have a JSON string, you can parse it by using the json.loads() method. The result will be a python dictionary.
Example: From json string to python objects
Here in output of the above program, input is string type and after parsing it, getting converted into dictionary (Python objects).
- Convert python objects to json string
If you have a python object, you can convert it into a JSON string by using the json.dumps() method.
Example: From python object to json strings.
- List of all the objects of python that can be converted into JSON strings.
In the above program, we are passing different-different types of python objects (dict, list, tuple, etc) in each json.dumps() method to convert it into json strings.
- Format the Result of JSON
The output of json is not easy to read, with no indentations and line breaks. The json.dumps() method has parameters to make it easier to read the results. Use indent parameter to define numbers of indent.
Example: Formatting the JSON result
In the above output, you can see when we are printing “x” then the resultant dictionary is printed in one line while when we are printing “y” value then its printing in format.
- Writing Python object in a JSON file.
json.dump() method is used to write in a json file.
Example : Writing in a JSON file.
Here output is written in a file “student_detail.json”
- Reading data as a python object from a JSON file.
To read a data from a JSON file, we have to use json.load() method.
Here we are getting output from “student_details.json” file as a python object.