Python: JSON decoding library that can associate decoded elements with the original line number?

I often use JSON for user editable configuration files. Malformed JSON, of course, took me for json.loads, but sometimes there are errors that I do not find until I go through the received dicts / lists / strings. I would like to be able to give useful errors, such as "Invalid value" foo on line 23 ", but when I get my answer, I lost any comparison with the original line numbers.

It seems possible that someone could write a JSON parser that marked each output object with some metadata about where it appeared in the input text: is there such a thing for python?

Example:

1. [{"foo": "x"},
2.  {"bar": "y"}]

After parsing the above, I found that “y” is not really a legal value for “bar”, and I would like to know that it came from line number 2.

+5
source share
2 answers

AFAIK, what you want does not exist, but I have an idea how you could implement it if you are interested ...

json , () . , . , Python 2.7+. Python JSON-, ( ) C.

, .

1) pure-python, json.JSONDecoder :

class PyDecoder(json.JSONDecoder):
    def __init__(self, encoding=None, object_hook=None, parse_float=None,
            parse_int=None, parse_constant=None, strict=True,
            object_pairs_hook=None):
        super(PyDecoder, self).__init__(encoding, object_hook, parse_float,
                                        parse_int, parse_constant, strict)
        self.scan_once = json.scanner.py_make_scanner(self)

2) , json.decoder.JSONObject , , .

0

json.load() , , , . ValueError, .

-1

All Articles