您的位置:首页 > 游戏 > 手游 > 网络公司哪家好_个人网页简单模板下载_如何购买域名_软文写作的技巧

网络公司哪家好_个人网页简单模板下载_如何购买域名_软文写作的技巧

2025/5/12 19:45:21 来源:https://blog.csdn.net/weixin_41997073/article/details/147286411  浏览:    关键词:网络公司哪家好_个人网页简单模板下载_如何购买域名_软文写作的技巧
网络公司哪家好_个人网页简单模板下载_如何购买域名_软文写作的技巧

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 实现的,无法直接查看源码。")

Source Code

/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)

skipkeys

Default is False

true时遇到非法key值进行跳过

import json# 定义一个包含非基本类型键的字典
data = {"name": "Alice",42: "The answer",3.14: "Pi",True: "Boolean True",None: "Null value",("tuple", "key"): "This will be skipped"  # 元组作为键,是非基本类型
}# 使用 json.dumps() 序列化字典,skipkeys=False(默认)
try:json_str_default = json.dumps(data)
except TypeError as e:print("Error with skipkeys=False:", e)# 使用 json.dumps() 序列化字典,skipkeys=True
json_str_skipkeys = json.dumps(data, skipkeys=True)# 输出结果
print("\nJSON string with skipkeys=True:")
print(json_str_skipkeys)data = {"name": "Alice",42: "The answer",3.14: "Pi",True: "Boolean True",None: "Null value"
}
json_str_default = json.dumps(data)
print(json_str_skipkeys)
result
Error with skipkeys=False: keys must be str, int, float, bool or None, not tuple
JSON string with skipkeys=True:
{"name": "Alice", "42": "The answer", "3.14": "Pi", "true": "Boolean True", "null": "Null value"}
{"name": "Alice", "42": "The answer", "3.14": "Pi", "true": "Boolean True", "null": "Null value"}

ensure_ascii

Default is True
import json# 定义一个包含非ASCII字符(中文)的Python字典
data = {"code": 1001, "name": "电波发", "description": "这是一个测试"}# 1. 当 ensure_ascii=False 时
json_str_no_escape = json.dumps(data, ensure_ascii=False, indent=4)
print("ensure_ascii=False 的输出:")
print(json_str_no_escape)# 2. 当 ensure_ascii=True 时(默认值)
json_str_escape = json.dumps(data, ensure_ascii=True, indent=4)
print("\nensure_ascii=True 的输出:")
print(json_str_escape)
result
{"code": 1001,"name": "电波发","description": "这是一个测试"
}{"code": 1001,"name": "\u7535\u6ce2\u53d1","description": "\u8fd9\u662f\u4e00\u4e2a\u6d4b\u8bd5"
}

check_circular

默认行为(check_circular=True):

import json# 创建一个包含循环引用的字典
data = {}
data['self'] = data  # 创建循环引用# 尝试序列化字典,check_circular=True(默认)
try:json_str_default = json.dumps(data, check_circular=True)  # 默认行为,实际上可以省略 check_circular 参数
except ValueError as e:print("Error with check_circular=True:", e)# 尝试序列化字典,check_circular=False
try:json_str_skip_check = json.dumps(data, check_circular=False)
except (OverflowError, RecursionError) as e:  # 可能抛出 OverflowError 或 RecursionErrorprint("Error with check_circular=False:", e)
result
Error with check_circular=True: Out of memory during dict size allocation
# (实际运行时更可能表现为:循环引用检测到,抛出 ValueError 类似提示逻辑错误的异常,
# 示例中直接写为内存分配错误仅为示意,核心是阻止序列化继续)
# 简化理解输出描述为:
Error with check_circular=True: Circular reference detectedError with check_circular=False: maximum recursion depth exceeded while calling a Python object
# (或 OverflowError,具体取决于 Python 解释器和环境,
# 核心是未检测循环引用导致无限递归)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com