rtyler / py-yajl

py-yajl provides Python bindings for the Yajl JSON encoder/decoder library
http://rtyler.github.com/py-yajl
74 stars 18 forks source link

decoding integers doesn't seem to work #22

Open ccheever opened 14 years ago

ccheever commented 14 years ago

If I encode and decode the integer 1, I get a ValueError:

In [9]: yajl.loads("1")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/tmp/py-yajl/<ipython console> in <module>()

ValueError: eof was met before the parse could complete

1 seems to be valid JSON according to http://www.jsonlint.com/ and also JSON.stringify(1) returns '1' and simplejson and cjson successfully decode '1' as 1.

Adding a newline or space to the end of the string fixes the problem.

In [20]: yajl.loads("1 ")
Out[20]: 1

In [18]: yajl.loads("1\n")
Out[18]: 1

Another reason why this behavior seems odd is that yajl.dumps(1) returns '1' which then can't be yajl.loads-ed. It seems like any output from yajl.dumps should be valid input to yajl.loads.

rtyler commented 14 years ago

The fact that this works with a newline or a space at the end of the string is likely a bug.

The reason yajl.loads("1") doesn't work is because it's a JSON fragment and not a JSON object. From json.org:

JSON is built on two structures:
    * A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
     * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

The other issue here is that ValueError isn't a descriptive error at all. I should correct that too

ccheever commented 14 years ago

Thanks Tyler.

I read the JSON spec after posting this, and what you write makes sense.

OTOH, the author of cjson notes:

'But cjson doesn't deal with "JSON texts" it deals with "JSON values", and I think it's far more useful this way'

http://pypi.python.org/pypi/python-cjson

Might be useful to have an option to handle JSON fragments correctly.

If you're being strict, you might also want to enforce that only dicts/lists can be passed to dumps or an Exception will get raised.

If I can get some time, I might submit a patch.