When sending HTTP requests, the Content-Type header must match the data format being sent:
JSON Format:
Content-Type: application/json
Request body: {"mobile_phone":"13164761466","pwd":"123456789"}
Usage: json=json_data
Form Data Format:
Content-Type: aplication/x-www-form-urlencoded
Request body: mobile_phone=13164761466&pwd=123456789
Usage: data=form_data
JSON Serialization in Python
Serialization converts Python data structures (dictionaries, lists) into JSON-formatted strings for use by other systems.
Converting Dictionary to JSON String:
import json
sample = {'username': 'john', 'status': None, 'is_active': False, 'is_admin': True}
result = json.dumps(sample)
print(result)
Output:
{"username": "john", "status": null, "is_active": false, "is_admin": true}
Key Type Conversions:
NonebecomesnullTruebecomestrueFalsebecomesfalse- Single quotes become double quotes
- Tuples and lists both convert to arrays
Example with Multiple Types:
import json
data = {'items': [1, 2, 'a'], 'coordinates': (1, 2), 'value': None, 'flag': False}
print(json.dumps(data))
Output:
{"items": [1, 2, "a"], "coordinates": [1, 2], "value": null, "flag": false}
JSON Deserialization in Python
Deserialization converts JSON strings back into Python dictionaries. Note that JSON keys must use double quotes.
import json
json_string = '{"name": "alice", "age": 25, "active": true}'
parsed_data = json.loads(json_string)
print(parsed_data)
Output:
{'name': 'alice', 'age': 25, 'active': True}
JavaScript JSON Methods Comparison
JavaScript JSON.parce():
Used when receiving JSON data from Python. It parses JSON strings into JavaScript objects.
JSON.parse('{"items": [1, 2, "a"], "result": null}')
JavaScript JSON.stringify():
Used when sending data to Python. It converts JavaScript objects into JSON strings.
JSON.stringify({name: 'bob', value: null})
This JSON string can then be parsed by Python's json.loads():
import json
js_output = '{"name": "bob", "value": null}'
python_data = json.loads(js_output)
print(python_data)
Output:
{'name': 'bob', 'value': None}
Advanced json.dumps() Parameters
Handling Non-ASCII Characters:
By default, json.dumps() escapes non-ASCII characters. Use ensure_ascii=False to preserve them.
import json
data = {'name': 'li', 'flag': True, 'greeting': 'hello'}
print(json.dumps(data))
Output (with default settings):
{"name": "li", "flag": true, "greeting": "\u4f60\u597d"}
Output (with ensure_ascii=False):
{"name": "li", "flag": true, "greeting": "hello"}
Compact Output with separators:
Remove extra whitespace using the separators parameter.
import json
data = {'name': 'li', 'flag': True, 'message': 'hello'}
print(json.dumps(data, ensure_ascii=False, separators=(",", ":")))
Output:
{"name":"li","flag":true,"message":"hello"}