KISSmetrics generates invalid JSON strings I need to parse. I'm getting tons of errors like
ERROR 2013-03-04 04:31:12,253 Invalid \escape: line 1 column 132 (char 132): {"search engine":"Google","_n":"search engine hit","_p":"z392cpdpnm6silblq5mac8kiugq=","search terms":"happy new year animation 1920\303\2271080 hd","_t":1356390128}
ERROR 2013-03-04 04:34:19,153 Invalid \escape: line 1 column 101 (char 101): {"search engine":"Google","_n":"ad campaign hit","_p":"byskpczsw6sorbmzqi0tk1uimgw=","search terms":"\331\203\330\261\330\252\331\207 \331\201\331\212\330\257\331\212\330\244\331\211 \330\256\331\212\331\204\330\247\330\255\331\211 \331\203\331\210\330\261\330\257\331\211","_t":1356483052}
My code is:
for line in lines:
try:
data = self.clean_data(json.loads(line))
except ValueError, e:
logger.error('%s: %s' % (e.message, line))
Example raw data:
{"search engine":"Google","_n":"search engine hit","_p":"kvceh84hzbhywcnlivv+hdztizw=","search terms":"military sound effects programs","_t":1356034177}
Is there any chance to cleanup this messy JSON and parse it? Thanks for your help.
Consider cjson for this exact scenario (https://pypi.python.org/pypi/python-cjson)
Seems to handle the escaped octals (and quick).
Your input data contains octal escapes; those would be invalid indeed. Replace them with decoded bytes using a regular expression:
This makes your input work:
I had similar problem and just replacing json library with yaml solved the issue. (YAML is compatible with JSON.)
Example: