Search code examples
pythonjsonlambdaf-string

Lambda f-string for JSON string?


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)

Solution

  • 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" } ] } ]'