On Wed, May 29, 2013 at 1:10 PM, Chris Rebert <c...@rebertia.com> wrote:
> On Wed, May 29, 2013 at 4:16 AM, Jabba Laci <jabba.l...@gmail.com> wrote: > > I have a growing JSON file that I edit manually and it might happen > > that I repeat a key. If this happens, I would like to get notified. > > Currently the value of the second key silently overwrites the value of > > the first. > > You can pass an appropriate object_pairs_hook function to json.load(): > http://docs.python.org/2/library/json.html#repeated-names-within-an-object > http://docs.python.org/2/library/json.html#json.load > That makes it pretty easy to provide any validation you might like to your JSON data. Here's a quick example that raises ValueError on duplicate keys, since the docs didn't have any examples. Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 >>> s = '{"x": 1, "x": 2, "x": 3}' >>> def json_checker(seq): d = {} for key, value in seq: if key in d: raise ValueError("Duplicate key %r in json document" % key) else: d[key]=value return d >>> json.loads(s, object_pairs_hook=json_checker) Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> json.loads(s, object_pairs_hook=checker) File "C:\Python32\lib\json\__init__.py", line 320, in loads return cls(**kw).decode(s) File "C:\Python32\lib\json\decoder.py", line 351, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python32\lib\json\decoder.py", line 367, in raw_decode obj, end = self.scan_once(s, idx) File "<pyshell#30>", line 5, in json_checker raise ValueError("Duplicate key %r in json document" % key) ValueError: Duplicate key 'x' in json document -- Jerry
-- http://mail.python.org/mailman/listinfo/python-list