0

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

1 Answer 1

2

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'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.