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.
file.write(v_data)asv_datais already a JSON encoded string."{\n \"firstName\": \"rob\",\n \"lastName\": \"bob\",\n \"dept\": [\"IT\"]\n }"json.dumptakes a Python dictionary, not a string. You could usev2_data = json.loads(v_data)which would return a dictionary{'firstName': 'rob', 'lastName': 'bob', 'dept': ['IT']}, that you can then use withjson.dumpwithv2_datathe dictionary, or just start with a dictionary, instead of a string