解决python的json模块不喜欢循环引用的问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了解决python的json模块不喜欢循环引用的问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2634字,纯文字阅读大概需要4分钟。
内容图文
![解决python的json模块不喜欢循环引用的问题](/upload/InfoBanner/zyjiaocheng/661/eda1bf1ac50e42d980e0d70227c2422d.jpg)
除了使用外部库(例如jsonpickle,虽然我没有尝试过),还有一种方法可以让python的json模块转储具有循环引用的字典(或列表等)(只是删除引用,是)?
我只想使用json更轻松地查看一些调试输出.
解决方法:
好吧,避免使用除标准模块之外的任何方法,这是一种利用repr处理循环引用的解决方案.编辑:有关最新,请参阅all-purpose function for dumping any python thing in a mostly-readable manner (aka dump)
# MAGIC-NUMBER: max length is just some guess at a reasonable size, e.g. 80 cols by 100 lines
def dump(value, msg='DUMP', max_length=80 * 100, stdout=False, pick=None):
"""
Write as verbose of a description of the value as possible to logging.DEBUG.
See https://stackoverflow.com/q/27830888/116891
:param value: The item of interest.
:type value: object
:param msg: Prefix for the logged item (default='DUMP')
:type msg: basestring
:param max_length: Longest allowed string length (set to None for unlimited)
:type max_length: int
:param stdout: If true, print instead of logging (default=False)
:type stdout: bool
:param pick: If specified, dump only values for these keys of the item
(value must be a dict or allow __dict__ access).
The name comes from http://underscorejs.org/#pick.
:type pick: iterable of basestring
:return: True if message dumped
:rtype: bool
"""
if not logging.getLogger().isEnabledFor(logging.DEBUG) and not stdout:
return
if pick:
d = value if isinstance(value, dict) else value.__dict__
filtered = {
property_name: d[property_name]
for property_name in pick
if property_name in d
}
value = filtered
kwargs = dict(indent=2, sort_keys=True)
try:
import json
info = json.dumps(value, **kwargs)
except:
# JSON doesn't like circular references :/
try:
string_repr = repr(value)
# Replace python primitives, single-quotes, unicode, etc
string_repr = string_repr .replace('None', 'null') .replace('True', 'true') .replace('False', 'false') .replace("u'", "'") .replace("'", '"')
# Replace object and function repr's like <MyObject ...>
string_repr = re.sub(r':(\s+)(<[^>]+>)', r':\1"\2"', string_repr)
# Replace tuples with lists, very naively
string_repr = string_repr.replace('(', '[').replace(')', ']')
info = json.dumps(json.loads(string_repr), **kwargs)
except:
from pprint import pformat
info = pformat(value, indent=2)
def _out(formatted_string, *format_args):
"""Format the string and output it to the correct location."""
if stdout:
print(formatted_string % format_args)
else:
logging.debug(formatted_string, *format_args)
if max_length is None or len(info) <= max_length:
_out('%s: %s', msg, info)
return True
else:
_out(
'Did not dump "%s" due to length restriction. Increase max_length if desired.', msg
)
return False
内容总结
以上是互联网集市为您收集整理的解决python的json模块不喜欢循环引用的问题全部内容,希望文章能够帮你解决解决python的json模块不喜欢循环引用的问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。