jsonc: handle parse errors from 'json' gracefully (fixes #2858)

- JSONDecodeError is only available in simplejson, use ValueError
- imporove error context output
This commit is contained in:
j 2015-11-12 13:01:29 +01:00
parent 3ed213d6d7
commit 98d83192ce

View file

@ -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)