Preface
In Python,json
andjsonify
It is two important tools for processing JSON data, but their usage scenarios and functions are different.
1. Overview of json and jsonify
json
It 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.jsonify
It 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=2
Indicates 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
:forTrue
When , 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)
anddumps
Similar, butdump
It is to write the serialized JSON data directly to the file objectfp
middle. For example:
with open('', 'w', encoding='utf-8') as f: (data, f, ensure_ascii=False, indent=4)
This code will generate aFile, content and above
dumps
The output is the same.
2. Deserialization (convert JSON format strings to Python objects)
(json_string)
Add strings in JSON formatjson_string
Convert 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'}
heredata
is a dictionary object.
(fp)
From file objectfp
Read 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 before
dump
The JSON data written by the method, after reading it heredata
It is also a dictionary object.
3. jsonify function in Flask
jsonify
It is a helper function provided by the Flask framework, specially used to convert Python objects into HTTP responses in JSON format. and()
compared to,jsonify
More concise and easy to use, it also automatically sets the HTTP response headerContent-Type
forapplication/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 header:
jsonify
The HTTP response header will be automatically setContent-Type
forapplication/json
,and()
Need to set manually.Compression processing:
jsonify
The 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 automaticallyusers
Convert 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:
json
The module is mainly used to process JSON data internally, such as file reading and writing or simple data exchange.jsonify
It 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.jsonify
These operations are automatically completed and compression processing is supported.
-
Applicable scenarios:
json
The module is suitable for any scenario where JSON data is required.jsonify
Suitable 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!