How to parse JSON in Python

JSON is a lightweight format that can be easily generated and readable by humans. it is language independent. Python provide a module called json which gives list of methods. Python dump() is an inbuild function which is used to parse JSON that returns json string.

Example:

property = '{"id": 1, "property_type": "apartment", "amenities": ["tv", "fridge"]}'

JSON is a subset of javascript obect notation. The syntax rules of JSON is as following:

  • Name/value pairs: JSON name is followed by ":" and the pair name/value is seprated by comma(,).
  • Curly braces: Hold objects
  • Square brackets: It holds the list of array with comma seprated.

Rules:

While creating JSON, It should be the following data types:

  • Object (JSON object)
  • String
  • Array
  • Number
  • Boolean
  • Null

Example:

{
  "marketing": [
    {
      "firstName": "Joe",
      "lastName": "Francis",
    },
    {
      "firstName": "Chandler",
      "lastName": "Bing",
    }
  ],
  "Tech": [
    {
      "firstName": "Monica",
      "lastName": "Geller",
    },
    {
      "firstName": "Ross",
      "lastName": "Geller",
    }
  ]
}

Parse JSON - Convert JSON to Python

JSON package provides inbuilt function called loads() which converts json string to python object. Below is the example.

Syntax:

json.loads(json_string)

Example:

# Json to Python object conversion

import json

# Json
property = '{"id": 1, "property_type": "apartment", "amenities": ["tv", "fridge"]}'

# Conversion
prop_obj = json.loads(property) 
print(prop_obj)

# output:
# {'id': 1, 'property_type': 'apartment', 'amenities': ['tv', 'fridge']}

print(type(prop_type))
# output
# <class 'dict'>