SoFunction
Updated on 2025-05-14

Detailed explanation of how to use json and jsonify in Python

Preface

In Python,jsonandjsonifyIt is two important tools for processing JSON data, but their usage scenarios and functions are different.

1. Overview of json and jsonify

jsonIt is a module in the Python standard library used to process JSON (JavaScript Object Notation) data. JSON is a lightweight data exchange format that can realize data interaction in different programming languages, which is easy to read and write by people, and is also easy to machine parse and generate.jsonifyIt is a function provided by the Flask framework to convert data into a response object in JSON format. It is mainly used to build routes that return JSON data in Flask applications.

2. Common methods of json module

1. Serialization (convert Python objects to JSON format string)

(1)(obj, ensure_ascii=True, indent=None, separators=None, sort_keys=False)

  • obj: Python objects to be serialized, such as dictionaries, lists, etc.

  • ensure_ascii: The default parameter isTrue, if set toFalse, non-ASCII characters can be output (such as Chinese characters), otherwise non-ASCII characters will be escaped.

  • indent: Used to specify indentation, which can make the output JSON string readable better. For example,indent=2Indicates indentation of 2 spaces.

  • separators: Used to specify the delimiter, the default is(',', ': '), the size of the generated JSON string can be reduced by setting other values.

  • sort_keys:forTrueWhen , it will be sorted in the order of the keys of the dictionary.

    For example:

     import json
     data = {'name': 'Zhang San', 'age': 30, 'city': 'Beijing'}
     json_str = (data, ensure_ascii=False, indent=2)
     print(json_str)

    Output:

     {
         "name": "Zhang San",
         "age": 30,
         "city": "Beijing"
     }

(2)(obj, fp, ensure_ascii=True, indent=None, separators=None, sort_keys=False)

anddumpsSimilar, butdumpIt is to write the serialized JSON data directly to the file objectfpmiddle. For example:

 with open('', 'w', encoding='utf-8') as f:
     (data, f, ensure_ascii=False, indent=4)

This code will generate aFile, content and abovedumpsThe output is the same.

2. Deserialization (convert JSON format strings to Python objects)

(json_string)

Add strings in JSON formatjson_stringConvert to Python object.

For example:

 json_str = '{"name": "Zhang San", "age": 30, "city": "Beijing"}'
 data = (json_str)
 print(data)

Output:

 {'name': 'Zhang San', 'age': 30, 'city': 'Beijing'}

heredatais a dictionary object.

(fp)

From file objectfpRead JSON data and convert it into Python objects. For example:

 with open('', 'r', encoding='utf-8') as f:
     data = (f)
 print(data)

AssumptionsThe file content was passed beforedumpThe JSON data written by the method, after reading it heredataIt is also a dictionary object.

3. jsonify function in Flask

jsonifyIt is a helper function provided by the Flask framework, specially used to convert Python objects into HTTP responses in JSON format. and()compared to,jsonifyMore concise and easy to use, it also automatically sets the HTTP response headerContent-Typeforapplication/json, ensure that the client can correctly parse the returned data.

Basic usage

 from flask import jsonify, Flask
 app = Flask(__name__)
 ​
 @('/index')
 def index():
     return jsonify({"home": "front page"})

Features

  • Automatically set response headerjsonifyThe HTTP response header will be automatically setContent-Typeforapplication/json,and()Need to set manually.

  • Compression processingjsonifyThe returned JSON data will be compressed, reducing the amount of data transmission and improving efficiency.

  • Simplify the code: Developers do not need to manually encapsulate the response object, they only need to pass a Python dictionary to generate a response in JSON format.

Example:

 @('/users')
 def get_users():
     users = [
         {"id": 1, "name": "Alice"},
         {"id": 2, "name": "Bob"}
     ]
     return jsonify(users)

Through the above code, Flask will automaticallyusersConvert the list to JSON format response and set the correct response header.

4. The difference between json and jsonify

Although both can be used to process JSON data, their usage scenarios and functions are different:

  • Different uses

    • jsonThe module is mainly used to process JSON data internally, such as file reading and writing or simple data exchange.

    • jsonifyIt is a tool provided by the Flask framework, specially used to generate HTTP responses in JSON format in Web development.

  • Functional differences

    • ()and()Response header and content type need to be set manually.

    • jsonifyThese operations are automatically completed and compression processing is supported.

  • Applicable scenarios

    • jsonThe module is suitable for any scenario where JSON data is required.

    • jsonifySuitable for web development under the Flask framework, especially when returning JSON data in the RESTful API.

Summarize

This is the article about the usage and differences between json and jsonify in Python. For more related content on Python json and jsonify, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!