0

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.

3
  • 1
    You should just file.write(v_data) as v_data is already a JSON encoded string. Commented Feb 11, 2020 at 4:34
  • I didn't found any problem The json is valid on evey validators. "{\n \"firstName\": \"rob\",\n \"lastName\": \"bob\",\n \"dept\": [\"IT\"]\n }" Commented Feb 11, 2020 at 4:36
  • Python json.dump takes a Python dictionary, not a string. You could use v2_data = json.loads(v_data) which would return a dictionary {'firstName': 'rob', 'lastName': 'bob', 'dept': ['IT']}, that you can then use with json.dump with v2_data the dictionary, or just start with a dictionary, instead of a string Commented Feb 11, 2020 at 4:38

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.