rkj
rkj

Reputation: 711

encoding string into json not working as expected

I am using below code to encode a string (after variable replacement) to json , but the final json coming as an Invalid json.

data = '''{
    "firstName": "%s",
    "lastName": "%s",
    "dept": ["IT"]
    }'''

v_data = data % ('rob','bob')

with open("new_file.json", 'w') as file:
    json.dump(v_data, file)

The content of the json file "new_file.json" shows as Invalid json.

Upvotes: 0

Views: 56

Answers (1)

FoviBot
FoviBot

Reputation: 60

json.dump changes a json to a string, while it is already a string, use:

data = '''{
    "firstName": "%s",
    "lastName": "%s",
    "dept": ["IT"]
    }'''

v_data = data % ('rob','bob')

with open("new_file.json", 'w') as file:
    file.write(v_data)

Upvotes: 3

Related Questions