Python 使用str.format_map()时超过最大字符串递归次数
我正在使用格式化一些字符串,但是当这个字符串包含引号时,我遇到了一个问题,甚至是转义。代码如下:Python 使用str.format_map()时超过最大字符串递归次数,python,json,string,Python,Json,String,我正在使用格式化一些字符串,但是当这个字符串包含引号时,我遇到了一个问题,甚至是转义。代码如下: class __FormatDict(dict): def __missing__(self, key): return '{' + key + '}' def format_dict(node, template_values): template_values = __FormatDict(template_values) for key, item i
class __FormatDict(dict):
def __missing__(self, key):
return '{' + key + '}'
def format_dict(node, template_values):
template_values = __FormatDict(template_values)
for key, item in node.items():
if isinstance(item, str):
node[key] = item.format_map(template_values)
对于reqular字符串(不包括方括号或引号),它可以工作,但是对于像“{\”libraries\”:[{\“file\”:\“bonjour.so\”,\“modules\”:[{\“name\”:\“hello\”}]}]}”这样的字符串,它会崩溃,并显示消息ValueError:Max string recursion exted
在格式化前使用json.dumps(item)
转义引号并不能解决问题。应该如何解决此问题?我正在修改从JSON文件中获得的字符串,我更愿意修复Python代码,而不是更新我使用的JSON文档。你不能对JSON数据使用\uuuu missing\uu
技巧。有很多问题。这是因为{…}
替换字段中的文本不仅仅被视为字符串。看看:
在替换字段中,代码>和:…
也有意义!进入这些部分的内容也有严格的限制
递归错误来自多个嵌套的{…}
占位符内的占位符内的占位符str.format()
和str.format\u map()
无法支持大量嵌套级别:
>>> '{foo:{baz: {ham}}}'.format_map({'foo': 'bar', 'baz': 's', 'ham': 's'})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Max string recursion exceeded
对于“空”属性,此操作失败:
>>> '{"foo...com": "bar[baz]", "ham": "eggs"}'.format_map(MissingDict())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Empty attribute in format string
>>'{“foo…com”:“bar[baz],“ham”:“eggs”}。格式映射(MissingDict())
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:格式字符串中的属性为空
简言之,该格式对{…}
花括号中包含的内容做了太多假设,假设JSON数据容易中断
我建议您改为使用一个更简单的模板系统,它可以被子类化;默认设置是查找并替换$identifier
字符串。你想做什么就做什么;替换已知的$identifier
占位符,但保留未知名称不变
>>> class FormatWrapper:
... def __init__(self, v):
... self.v = v
... def __format__(self, spec):
... return '{{{}{}}}'.format(self.v, (':' + spec) if spec else '')
... def __getitem__(self, key):
... return FormatWrapper('{}[{}]'.format(self.v, key))
... def __getattr__(self, attr):
... return FormatWrapper('{}.{}'.format(self.v, attr))
...
>>> class MissingDict(dict):
... def __missing__(self, key):
... return FormatWrapper(key)
...
>>> '{"foo.com": "bar[baz]", "ham": "eggs"}'.format_map(MissingDict())
'{"foo.com": "bar[baz]", "ham": "eggs"}'
>>> '{"foo .com": "bar [ baz ]", "ham": "eggs"}'.format_map(MissingDict())
'{"foo .com": "bar [ baz ]", "ham": "eggs"}'
>>> '{"foo...com": "bar[baz]", "ham": "eggs"}'.format_map(MissingDict())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Empty attribute in format string