0

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)
Chris
  • 500
  • 6
  • 25
  • 1
    `{}` braces have special meaning in f-strings. You need to double them up when you don't want them replaced with the value of an expression. That is, every left and right bracket in your string needs to be written `{{` and `}}` except for the ones in `{x}` – kindall Nov 23 '21 at 00:55
  • 1
    It's easier to use `body.replace("lorem ipsum", "1 2 3")`, f-strings require escaping as others mentioned. – vladsiv Nov 23 '21 at 00:58

2 Answers2

3

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" } ] } ]'
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
1

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"}]}]'
chepner
  • 497,756
  • 71
  • 530
  • 681