JSON 字符串的 Lambda f 字符串?

Lambda f-string for JSON string?

我在 python 中有一个 JSON body 字符串,其中包含 lorem ipsum 例如

body = '[{ "type": "paragraph", "children": [ { "text": "lorem ipsum" } ] } ]'

我想创建一个 lambda f 字符串,它可以接受任何字符串并将其放在 lorem ipsum 所在的位置。例如

# Returns '[{ "type": "paragraph", "children": [ { "text": "1 2 3" } ] } ]'
body("1 2 3")

这可能吗?我尝试了以下但没有成功:

# 1
# SyntaxError: f-string: expressions nested too deeply
body = lambda x: f'''[{ "type": "paragraph", "children": [ { "text": "{x}" } ] } ]'''

# 2
# KeyError: ' "type"'
content = '[{ "type": "paragraph", "children": [ { "text": "{x}" } ] } ]'
body = lambda x: content.format(x=x)

您需要转义大括号才能使其正常工作。

>>> body = lambda x: f'[{{ "type": "paragraph", "children": [ {{ "text": "{x}" }} ] }} ]'
>>> body("1 2 3")
'[{ "type": "paragraph", "children": [ { "text": "1 2 3" } ] } ]

但是它要求每个大括号都用另一个大括号转义,这使得代码更难阅读。相反,您可以考虑使用支持 $-based substitutions

string.Template
>>> from string import Template
>>> body = '[{ "type": "paragraph", "children": [ { "text": "$placeholder" } ] } ]'
>>>
>>> s = Template(body)
>>> s.substitute(placeholder="CustomPlaceHolder")
'[{ "type": "paragraph", "children": [ { "text": "CustomPlaceHolder" } ] } ]'

jq 库解决了这个问题:

>>> import jq
>>> body = '[{ "type": "paragraph", "children": [ { "text": . } ] } ]'
>>> jq.text(body, "1 2 3")
'[{"type": "paragraph", "children": [{"text": "1 2 3"}]}]'