From 3e1da968eac02abd524c4a24b103b0cb3fe82a6d Mon Sep 17 00:00:00 2001 From: Will Thompson Date: Thu, 12 Nov 2015 11:03:55 +0000 Subject: [PATCH] jsonc: handle parse errors from 'json' gracefully (fixes #2858) A bit gnarly. I've manually tested this both with and without simplejson installed. --- ox/jsonc.py | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/ox/jsonc.py b/ox/jsonc.py index 9006d5c..d211bba 100644 --- a/ox/jsonc.py +++ b/ox/jsonc.py @@ -3,10 +3,17 @@ # 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 +# 'simplejson' defines a specific exception with attributes for the source position. +# 'json' does not. +_JSONDecodeError = getattr(json, '_JSONDecodeError', ValueError) + + def load(f): return loads(f.read()) @@ -14,8 +21,26 @@ 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 _JSONDecodeError as e: + if _JSONDecodeError == ValueError: + msg = e.message + lineno = None + colno = None + + try: + m = re.search(r'line (\d+) column (\d+)', msg) + if m: + (lineno, colno) = map(int, m.groups()) + except: + pass + else: + msg = e.msg + lineno = e.lineno + colno = e.colno + + if lineno and colno: + s = minified.split('\n') + context = s[lineno-1][max(0, colno-1):colno+30] + msg = msg + ' at ' + context + + raise ValueError(msg) -- 2.5.0