1、正常操作
# 打印出JSON import json from pprint import pprint data = { "name": "Tom", "age": 23, "gender": "man" } print(data) # {'name': 'Tom', 'age': 23, 'gender': 'man'} pprint(data) # {'age': 23, 'gender': 'man', 'name': 'Tom'}
2、序列化后再打印
print(json.dumps(data)) # {"name": "Tom", "age": 23, "gender": "man"} print(json.dumps(data, indent=2)) """ { "name": "Tom", "age": 23, "gender": "man" } """
3、打印包含中文的Json
Python2下的示例,Python3则没那么多问题了
# -*- coding: utf-8 -*- import json data = { "姓名": "王安石", "年龄": 42, "朝代": "宋代" } # 直接打印 print(data) # {'\xe5\xb9\xb4\xe9\xbe\x84': 42, # '\xe6\x9c\x9d\xe4\xbb\xa3': '\xe5\xae\x8b\xe4\xbb\xa3', # '\xe5\xa7\x93\xe5\x90\x8d': '\xe7\x8e\x8b\xe5\xae\x89\xe7\x9f\xb3'} # 序列化后再打印 print(json.dumps(data, ensure_ascii=False, indent=2)) """ { "年龄": 42, "朝代": "宋代", "姓名": "王安石" } """