Single quoted string to dictionary

Json.loads(string) expects double quoted string as parameter. If you have a string with single quotes, and try to use json.loads(), it will give you an error as single quoted string is not treated as valid JSON. This case may happen when you store a json string in database and try to create json from the string saved in the database.

string = "{'id': 'pay_123XYZ', 'entity': 'payment', 'amount': 120000, 'currency': 'INR', 'status': 'authorized'}"

If you want to create an object with above input, you can use ast module.

string = string if string else "{}" # else condition is added to handle cases when string is None
return ast.literal_eval(string)

If you check type(ast.literal_eval(string)), It will be of dict type.

{'id': 'pay_123XYZ', 'entity': 'payment', 'amount': 120000, 'currency': 'INR', 'status': 'authorized'}


Leave a Reply

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

Back to Top