How Do You Troubleshoot the Python Error “json.decoder.JSONDecode..”Expecting property name enclosed in double quotes…”?

Problem scenario
You are running a Python program that uses "import json". You get this error: "json.decoder.JSONDecode.."Expecting property name enclosed in double quotes…" You are not allowed to use bson, but you can use other Python packages. What should you do?

This solution only works if you can eliminate single quotes in the content to be serialized (or translated into JSON). This will get rid of single quotes indiscriminately.

Where "foobar" is the variable with the string you want to turn into JSON, do this:

import re, json
modifiedfoobar = foobar.replace("'", '"')   # (1)
latestagefoobar = json.dumps(modifiedfoobar)
finalfoobar = json.loads(latestagefoobar)

# (1) this eliminates single quotes. This may cause you problems if single quotes were part of the necessary content.
# If the string had single quotes instead of double quotes, this will save you from installing/importing bson.
# Often double quotes can be used instead of single quotes, but not always. If they are not interchangeable cannot, you may need bson.

Leave a comment

Your email address will not be published. Required fields are marked *