简体   繁体   中英

fstring in JSON, ValueError: Invalid format specifier, Python

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

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM