From 98d83192ce727dadbda71ea05e37d4b4ba1034d2 Mon Sep 17 00:00:00 2001 From: j <0x006A@0x2620.org> Date: Thu, 12 Nov 2015 13:01:29 +0100 Subject: [PATCH] jsonc: handle parse errors from 'json' gracefully (fixes #2858) - JSONDecodeError is only available in simplejson, use ValueError - imporove error context output --- ox/jsonc.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/ox/jsonc.py b/ox/jsonc.py index 9006d5c..83751ea 100644 --- a/ox/jsonc.py +++ b/ox/jsonc.py @@ -3,6 +3,8 @@ # vi:si:et:sw=4:sts=4:ts=4 from __future__ import with_statement, print_function +import re + from .js import minify from .utils import json @@ -14,8 +16,18 @@ def loads(source): try: minified = minify(source) return json.loads(minified) - except json.JSONDecodeError as e: - s = minified.split('\n') - context = s[e.lineno-1][max(0, e.colno-1):e.colno+30] - msg = e.msg + ' at ' + context - raise json.JSONDecodeError(msg, minified, e.pos) + except ValueError as e: + msg = e.message if hasattr(e, 'message') else str(e) + lineno = None + colno = None + try: + m = re.search(r'line (\d+) column (\d+)', msg) + if m: + (lineno, colno) = map(int, m.groups()) + except: + pass + if lineno and colno: + s = minified.split('\n') + context = s[lineno-1][max(0, colno-30):colno+30] + msg += ' at:\n\n %s\n %s\033[1m^\033[0m' %(context, ' ' * (colno - max(0, colno-30) - 2)) + raise ValueError(msg)