Reputation: 4311
I have the following code:
import json
domain="abc.com"
rawlog = json.loads(
f'{"domain": ${domain}}')
print(rawlog["domain"])
Which gives me:
Traceback (most recent call last):
File "<string>", line 6, in <module>
ValueError: Invalid format specifier
>
The question is, what is the cause and if I can have fstring in Json? I'm using the newest Python: python3 --version
shows Python 3.10.4
.
I also tried:
import json
domain="abc.com"
rawlog = json.loads('{"domain": f'{domain}'}')
print(rawlog["domain"])
but it gives:
File "<string>", line 5
rawlog = json.loads('{"domain": f'domain'}')
^
SyntaxError: invalid syntax
Upvotes: 0
Views: 387
Reputation: 36680
As {
and }
have special meaning they need to be escaped to mean literal {
and literal }
, consider following simple example
import json
domain="abc.com"
string=f'{{"domain": "{domain}"}}'
parsed=json.loads(string)
print(parsed)
gives output
{'domain': 'abc.com'}
Upvotes: 2