×
Post thumbnail

Python Json Module - a very important Module in Python.

Basic Functions
  1. **json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, kw)

    • Serializes obj as a JSON formatted stream to fp (a .write()-supporting file-like object).
    • Example:
      import json
      
      data = {'name': 'John', 'age': 30, 'city': 'New York'}
      with open('data.json', 'w') as file:
          json.dump(data, file)
      
  2. **json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, kw)

    • Serializes obj to a JSON formatted str.
    • Example:
      import json
      
      data = {'name': 'John', 'age': 30, 'city': 'New York'}
      json_string = json.dumps(data)
      print(json_string)  # Output: {"name": "John", "age": 30, "city": "New York"}
  3. **json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, kw)

    • Deserializes fp (a .read()-supporting file-like object containing a JSON document) to a Python object.
    • Example:
      import json
      
      with open('data.json', 'r') as file:
          data = json.load(file)
      print(data)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
      
  4. **json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, kw)

    • Deserializes s (a str, bytes, or bytearray instance containing a JSON document) to a Python object.
    • Example:
      import json
      
      json_string = '{"name": "John", "age": 30, "city": "New York"}'
      data = json.loads(json_string)
      print(data)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
      
Advanced Functions
  1. json.JSONEncoder

    • Extensible JSON encoder for Python data structures.
    • Example:
      import json
      
      class CustomEncoder(json.JSONEncoder):
          def default(self, obj):
              if isinstance(obj, set):
                  return list(obj)
              return super().default(obj)
      
      data = {'fruits': {'apple', 'banana'}}
      json_string = json.dumps(data, cls=CustomEncoder)
      print(json_string)  # Output: {"fruits": ["apple", "banana"]}
      
  2. json.JSONDecoder

    • Extensible JSON decoder for Python data structures.
    • Example:
      import json
      
      class CustomDecoder(json.JSONDecoder):
          def __init__(self, *args, **kwargs):
              super().__init__(object_hook=self.object_hook, *args, **kwargs)
      
          def object_hook(self, obj):
              if 'fruits' in obj:
                  obj['fruits'] = set(obj['fruits'])
              return obj
      
      json_string = '{"fruits": ["apple", "banana"]}'
      data = json.loads(json_string, cls=CustomDecoder)
      print(data)  # Output: {'fruits': {'apple', 'banana'}}
      
Common Use Cases
  1. Reading from and Writing to JSON Files

    • Example:
      import json
      
      data = {'name': 'Alice', 'age': 25, 'city': 'London'}
      
      # Writing to a JSON file
      with open('data.json', 'w') as file:
          json.dump(data, file, indent=4)
      
      # Reading from a JSON file
      with open('data.json', 'r') as file:
          data = json.load(file)
      print(data)  # Output: {'name': 'Alice', 'age': 25, 'city': 'London'}
      
  2. Handling Complex Data Types

    • Example:
      import json
      from datetime import datetime
      
      def datetime_converter(o):
          if isinstance(o, datetime):
              return o.__str__()
      
      data = {'event': 'Birthday', 'date': datetime.now()}
      json_string = json.dumps(data, default=datetime_converter)
      print(json_string)  # Output: {"event": "Birthday", "date": "2023-01-01 12:00:00"}
      
  3. Pretty Printing JSON

    • Example:
      import json
      
      data = {'name': 'Bob', 'age': 28, 'city': 'Paris'}
      json_string = json.dumps(data, indent=4)
      print(json_string)
      # Output:
      # {
      #     "name": "Bob",
      #     "age": 28,
      #     "city": "Paris"
      # }
      

       

  4. Sorting Keys in JSON

    • Example:
      import json
      
      data = {'name': 'Eve', 'age': 22, 'city': 'Berlin'}
      json_string = json.dumps(data, sort_keys=True)
      print(json_string)  # Output: {"age": 22, "city": "Berlin", "name": "Eve"}
      
Interview Tips that you can keep in mind 🧠
  1. Understand the differences between dump/load and dumps/loads: dump/load work with file-like objects, while dumps/loads work with strings.
  2. Know how to handle non-serializable data types: Use custom encoder/decoder or default argument in json.dumps.
  3. Practice reading and writing JSON data: Be comfortable with common operations such as pretty printing, sorting keys, and handling complex data structures.
  4. Be prepared to explain JSON data structures: Understand JSON's data types (objects, arrays, strings, numbers, booleans, null) and how they map to Python data types.

And that's it.

I hope this will be a part of your vast knowledge 📚

• • •

Latest Opinions

No Opinion so far...

End.

No internet connection

Trying to reconnect...

Loading...