Python json

JSON introduction

JSON v/s Python

  • JSON format is similar to dict notation in Python
  • Fields are always enclosed only by double quote " character
  • Instead of True there is true (lowercase)
  • Instead of False there is false (lowercase)
  • Instead of None there is null
  • list is known as array (despite the same syntax)
  • dict is known as object (despite the same syntax)
  • There is no tuple or set
  • Coma , is not allowed after the last element in list or object
  • camelCase is convention, although snake_case is also valid

convert JSON string to python dictionary

  • use json.loads(json_string) to convert string to python dict.
  • lets see an example
import json

data_str = '{"name":"Apple", "cost": 30}'

data = json.loads(data_str)
# output: <class 'dict'>
# output: Apple

convert python objects to JSON string

  • use json.dumps(obj) to convert python object to JSON string
  • let's look at an example
import json

students = ["Anji", "David", "Paul"]

data_str = json.dumps(students)
# output: <class 'str'>
# output: ["Anji", "David", "Paul"]

write JSON to file - json.dump

  • use json.dump(data, file) to write the data to file.
  • let's look at an example
import json

data = {"students": ["Travis", "Sudhakar", "Devika"]}

file_path = "/tmp/data.json"
with open(file_path, "a+") as _file:
    json.dump(data, _file)
  • open the file and we can find {"students": ["Travis", "Sudhakar", "Devika"]} as the text content.

load JSON data from file to memory - json.load

  • use json.load() to load data from file to memory
  • let's look at the below code
import json

data = None
with open(file_path, "r") as _file:
    data = json.load(_file)
# output: {'students': ['Travis', 'Sudhakar', 'Devika']}