Home > database >  Python - parsing JSON and f string
Python - parsing JSON and f string

Time:06-15

I am trying to write a small JSON script that parses JSON files. I need to include multiple variables in the code but currently, I'm stuck since f string does not seem to be working as I expected. Here is an example code:

import json

test = 10
json_data = f'[{"ID": {test},"Name":"Pankaj","Role":"CEO"}]'

json_object = json.loads(json_data)

json_formatted_str = json.dumps(json_object, indent=2)

print(json_formatted_str)

The above code returns an error:

json_data = f'[{"ID": { {test} },"Name":"Pankaj","Role":"CEO"}]'
ValueError: Invalid format specifier

Could you, please let me know how can I add variables to the JSON?

Thank you.

CodePudding user response:

You can put extra{ and } to your string:

import json

test = 10
json_data = f'[{{"ID": {test},"Name":"Pankaj","Role":"CEO"}}]'

json_object = json.loads(json_data)
json_formatted_str = json.dumps(json_object, indent=2)
print(json_formatted_str)

Prints:

[
  {
    "ID": 10,
    "Name": "Pankaj",
    "Role": "CEO"
  }
]
  • Related