Python-JSON(Javascript Object Notation)

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

import json

  • 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

Output:

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.

Output

  • List of all the objects of python that can be converted into JSON strings.
  1. dict
  2. tuple
  3. list
  4. string
  5. int
  6. Float
  7. True
  8. False
  9. None

Example:

Output

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.

  • When we convert from python to JSON, python objects are converted into the JSON (javascript) equivalent:
Python JSON
dictobject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull
  • 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

Output

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.

Output

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.

Example:

Output

Here we are getting output from “student_details.json” file as a python object.

Leave a Comment

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock