One Hell Named JSON

time to read 1 min | 157 words

Today on my AWS Lambda Python function, its suffering from an error ValueError: Expecting property name: line 1 column 2 (char 1). This function receive a json events from AWS Kinesis and send it back to kafka. Apperently this is an error from json.loads if you have a json strings with a single quote

>>> json_string = "{'name': rezha, 'ganteng': true}"
>>> json.loads(json_string)
# ValueError: Expecting property name: line 1 column 2 (char 1)

To fix this, you could use ast.literal_eval. ast.literal_eval safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets. ast.literal_eval raises an exception if the input isn’t a valid Python datatype, so the code won’t be executed if it’s not.

Use ast.literal_eval whenever you need eval. You shouldn’t usually evaluate literal Python statements.