【星海随笔】Python-JSON数据的处理
JSON 是一种轻量级的数据交换格式,主要用于在客户端和服务器之间传输数据。
JSON 在 python 里是一个标准库
https://www.jyshare.com/compile/9/
import json
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
json_string = json.dumps(data)
print(json_string)json_data = '{"name": "Bob", "age": 25, "city": "Los Angeles"}'
python_obj = json.loads(json_data)
print(python_obj)
{“name”: “Alice”, “age”: 30, “city”: “New York”} #Json格式
{‘name’: ‘Bob’, ‘age’: 25, ‘city’: ‘Los Angeles’} #Python对象
#如果使用str修改双引号为单引号,则并不能转换为Dict模式
json.dumps(obj): 将 Python 对象转换为 JSON 格式的字符串。
json.loads(s): 将 JSON 格式的字符串转换为 Python 对象。
json.dump(obj, fp): 将 Python 对象写入文件(以 JSON 格式)。
json.load(fp): 从文件中读取 JSON 格式的数据并转换为 Python 对象。
注:Json 是轻量级的 无法直接序列化 datetime 格式,需要使用其他方式进行对 datetime 的格式进行自定义处理。例如:修改 Super 继承 DateTimeEncoder 或者 datetime 转化为 str 。
方法1
import json
from datetime import datetimeclass DateTimeEncoder(json.JSONEncoder):def default(self, obj):if isinstance(obj, datetime):return obj.isoformat() # 或者使用其他格式化方法return super().default(obj)data = {'name': 'Alice','timestamp': datetime.now()
}json_str = json.dumps(data, cls=DateTimeEncoder)
print(json_str)
方法2
from datetime import datetime, timezone
# 创建一个包含时区信息的 datetime 对象
dt_with_tz = datetime(2023, 10, 5, 14, 48, 0, tzinfo=timezone.utc)# 使用 isoformat() 方法格式化为字符串
dt_str_with_tz = dt_with_tz.isoformat()
print(dt_str_with_tz) # 输出: '2023-10-05T14:48:00+00:00'# 创建一个不包含时区信息的 datetime 对象
dt_without_tz = datetime(2023, 10, 5, 14, 48, 0)# 使用 isoformat() 方法格式化为字符串
dt_str_without_tz = dt_without_tz.isoformat()
print(dt_str_without_tz) # 输出:" "
Supports six types of data structures
字符串(string)
数字(number)
对象(object,即键值对)
数组(array)
布尔值(true/false)
空值(null)
check source code
import inspect
import json# 查看 json 模块的源码文件路径(仅适用于纯 Python 模块)
print(json.__file__)# 查看 json.dumps 函数的源码
try:print(inspect.getsource(json.dumps))
except TypeError:print("该函数可能是用 C 实现的,无法直接查看源码。")
/usr/local/python-3.8.1/lib/python3.8/json/__init__.py
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,allow_nan=True, cls=None, indent=None, separators=None,default=None, sort_keys=False, **kw):"""Serialize ``obj`` to a JSON formatted ``str``.If ``skipkeys`` is true then ``dict`` keys that are not basic types(``str``, ``int``, ``float``, ``bool``, ``None``) will be skippedinstead of raising a ``TypeError``.If ``ensure_ascii`` is false, then the return value can contain non-ASCIIcharacters if they appear in strings contained in ``obj``. Otherwise, allsuch characters are escaped in JSON strings.If ``check_circular`` is false, then the circular reference checkfor container types will be skipped and a circular reference willresult in an ``OverflowError`` (or worse).If ``allow_nan`` is false, then it will be a ``ValueError`` toserialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) instrict compliance of the JSON specification, instead of using theJavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).If ``indent`` is a non-negative integer, then JSON array elements andobject members will be pretty-printed with that indent level. An indentlevel of 0 will only insert newlines. ``None`` is the most compactrepresentation.If specified, ``separators`` should be an ``(item_separator, key_separator)``tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and``(',', ': ')`` otherwise. To get the most compact JSON representation,you should specify ``(',', ':')`` to eliminate whitespace.``default(obj)`` is a function that should return a serializable versionof obj or raise TypeError. The default simply raises TypeError.If *sort_keys* is true (default: ``False``), then the output ofdictionaries will be sorted by key.To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the``.default()`` method to serialize additional types), specify it withthe ``cls`` kwarg; otherwise ``JSONEncoder`` is used."""# cached encoderif (not skipkeys and ensure_ascii andcheck_circular and allow_nan andcls is None and indent is None and separators is None anddefault is None and not sort_keys and not kw):return _default_encoder.encode(obj)if cls is None:cls = JSONEncoderreturn cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,check_circular=check_circular, allow_nan=allow_nan, indent=indent,separators=separators, default=default, sort_keys=sort_keys,**kw).encode(obj)