Python- JSON

In Python, JSON exists as a string (It’s also common to store a JSON object in a file). For example:

p = '{"name": "Bob", "languages": ["Python", "Java"]}'

Parse JSON in Python

The built-in JSON module in Python provides functions for encoding Python objects into JSON strings and decoding JSON strings back into Python objects.

json.loads()

Parses a JSON string and converts it into a Python dictionary .

import json
 
person = '{"name": "Bob", "languages": ["English", "French"]}'
person_dict = json.loads(person)
 
print(f'person_dict: {person_dict}') # {'name': 'Bob', 'languages': ['English', 'French']}
print(f'languages: {person_dict["languages"]}') # ['English', 'French']

json.load()

Reads a file containing a JSON object and converts it into a Python dictionary

# person.json
{"name": "Bob", 
"languages": ["English", "French"]
}
with open('./person.json', 'r') as f:
  data = json.load(f)
 
print(f'data: {data}') # {'name': 'Bob', 'languages': ['English', 'French']}

json.dumps()

Serializes a Python object into a JSON formatted string.

person_dict = {'name': 'Bob',
'age': 12,
'children': None
}
 
person_json = json.dumps(person_dict)
print(f'person_json: {person_json}') # {"name": "Bob", "age": 12, "children": null}

json.dump()

https://www.geeksforgeeks.org/use-jsonify-instead-of-json-dumps-in-flask/ Serializes a JSON object and writes it to a file

person_dict = {"name": "Bob",
"languages": ["English", "French"],
"married": True,
"age": 32
}
 
with open('person.txt', 'w') as json_file:
  json.dump(person_dict, json_file)
# person.txt: {"name": "Bob", "languages": ["English", "French"], "married": true, "age": 32}

jsonify()

https://www.geeksforgeeks.org/use-jsonify-instead-of-json-dumps-in-flask/

jsonify() is a Flask utility that converts a Python dictionary (or any other serializable data structure) into a JSON response object. This function not only serializes the data but also sets the correct MIME type for the response (i.e., application/json), making it suitable for API responses.

  • Return Type: While json.dumps() returns a string, jsonify() returns a Flask Response object.
  • MIME Type: jsonify() automatically sets the response’s content type to application/json, whereas json.dumps() does not.
from flask import Flask, jsonify
 
app = Flask(__name__)
 
@app.route('/api/person', methods=['GET'])
def get_person():
    person_dict = {
        'name': 'Bob',
        'age': 12,
        'children': None
    }
    return jsonify(person_dict)
 
if __name__ == '__main__':
    app.run(debug=True)

Use Cases:

  • Use json.dumps() when you need to serialize data to a JSON string for logging, file storage, or sending via protocols that do not require HTTP.
  • Use jsonify() when you want to send JSON data as an HTTP response in a Flask application.