Python Gotcha's?

Roy Smith roy at panix.com
Thu Apr 5 08:32:10 EDT 2012


In article <4f7d896f$0$29983$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> > You mean JSON expects a string with valid JSON? Quelle surprise.
> 
> No. The surprise is that there exists a tool invented in the 21st century 
> that makes a distinction between strings quoted with " and  those quoted 
> with '. Being used to a sensible language like Python, it boggled my 
> brain the first time I tried to write some JSON and naturally treated the 
> choice of quote mark as arbitrary.

Your brain has a low boggle threshold.

There's absolutely no reason why JSON should follow Python syntax rules.  
Making it support either kind of quotes would have complicated every 
JSON library in the world, for no added value.  Nobody should ever be 
hand-writing JSON (just like nobody should ever be hand-writing XML).  
Just use the supplied library calls and you'll never have to worry about 
low-level minutia like this again.

> It especially boggled my brain when I 
> saw the pathetically useless error message generated:
> 
> py> json.loads("{'test':'test'}")
> [...]
> ValueError: Expecting property name: line 1 column 1 (char 1)
> 
> "Expecting property name"??? WTF???

One of the hardest things about writing parsers is generating helpful 
error messages when things don't parse.  But, it's only of value to do 
that when you're parsing something you expect to be written by a human, 
and thus a human has to puzzle out what they did wrong.  Nobody expects 
that a JSON parser will be parsing human-written input, so there's 
little value to saying anything more than "parse error".

> The reason this is a Gotcha rather than a bug is because the JSON 
> standard specifies the behaviour (probably in order to be compatible with 
> Javascript).

Well, considering that the JS in JSON stands for JavaScript...

> Hence, although the behaviour is mind-numbingly stupid, it 
> is deliberate and not a bug. Hence, a gotcha.

But surely not a Python gotcha.  If anything, it's a JSON gotcha.  The 
same is true with PHP's JSON library, and Ruby's, and Perl's, and 
Scala's, and C++'s, and so on.  It's a JSON issue, and a silly one to be 
complaining about at that.



More information about the Python-list mailing list