Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #46427 > unrolled thread

Re: detect key conflict in a JSON file

Started byJerry Hill <malaclypse2@gmail.com>
First post2013-05-29 23:43 -0400
Last post2013-05-29 23:43 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: detect key conflict in a JSON file Jerry Hill <malaclypse2@gmail.com> - 2013-05-29 23:43 -0400

#46427 — Re: detect key conflict in a JSON file

FromJerry Hill <malaclypse2@gmail.com>
Date2013-05-29 23:43 -0400
SubjectRe: detect key conflict in a JSON file
Message-ID<mailman.2391.1369885409.3114.python-list@python.org>

[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​

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web