Home > Enterprise >  How to format a json data with dynamic variable using python
How to format a json data with dynamic variable using python

Time:06-03

I am preparing a json data dynamically in Python meaning pass_over can change anytime. I just provided an example below which makes it fixed Each time I pass tester variable to an api call all i get is

valueError: invalid format specifier

Here is my code

    pass_over = '000067895'

    tester = f'''{
              "custId": {pass_over},
              "acctStatusCriterion": [
                {
                  "acctType": "YY",
                  "acctStatus": "Open"
                },
                {
                  "acctType": "VV",
                  "acctStatus": "Open"
                },
              ],
              "incExtAcctInfoFlag": true 
            }'''
            

What am i doing wrong? can't I use the f string in python. Is this json format not correct?

CodePudding user response:

The problem with your code is the brackets (all of them), the f string considers what's inside them a variable (they are used as format specifiers) and not only the one with the variable you intend to change. To solve this, use double brackets in all the ones you wish to ignore, like :

pass_over = '000067895'

tester = f'''{{
            "custId": '{pass_over}',
            "acctStatusCriterion": [
            {{
                "acctType": "YY",
                "acctStatus": "Open"
            }},
            {{
                "acctType": "VV",
                "acctStatus": "Open"
            }},
            ],
            "incExtAcctInfoFlag": true 
        }}'''

print(tester)

output:

    {
        "custId": '000067895',
        "acctStatusCriterion": [
        {
            "acctType": "YY",
            "acctStatus": "Open"
        },
        {
            "acctType": "VV",
            "acctStatus": "Open"
        },
        ],
        "incExtAcctInfoFlag": true
    }
  • Related