Home > Blockchain >  Lambda f-string for JSON string?
Lambda f-string for JSON string?

Time:11-23

I have a JSON body string in python that contains lorem ipsum e.g.

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

I want to create a lambda f-string that can take any string and place it where lorem ipsum is. E.g.

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

Is this possible? I've tried the following but no luck:

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

CodePudding user response:

You need to escape the braces to make that work.

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

But it require each brace to be escaped with another brace making the code harder to read. Instead you can consider using string.Template which support $-based substitutions

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

CodePudding user response:

The jq library solves this problem:

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