Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #46427
| References | <CAOuJsMn38V2Gw3s=KMLJ+t4uFyu3GdzYyA-_TNiEqn7hWxNEjA@mail.gmail.com> <CAMZYqRT0F6i72Wozw8q3vfgi4xo7-ZtUEMJ6Q=9=ypRGvH_vQw@mail.gmail.com> |
|---|---|
| Date | 2013-05-29 23:43 -0400 |
| Subject | Re: detect key conflict in a JSON file |
| From | Jerry Hill <malaclypse2@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2391.1369885409.3114.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
On Wed, May 29, 2013 at 1:10 PM, Chris Rebert <clp2@rebertia.com> wrote:
> On Wed, May 29, 2013 at 4:16 AM, Jabba Laci <jabba.laci@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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: detect key conflict in a JSON file Jerry Hill <malaclypse2@gmail.com> - 2013-05-29 23:43 -0400
csiph-web