Permalink
Browse files

When dealing with numbered keys in dictionaries, convert them to strings

Per issue #10, this is in line with the Python `json` module behavior:

    >>> import json
    >>> json.dumps({1:2})
    '{"1": 2}'
    >>> json.dumps({1.2:2})
    '{"1.2": 2}'

Change-Id: Idd5c10e884227c5f82f19c6eabf083059f97950e
  • Loading branch information...
1 parent b6f7e32 commit f40427c52c0b2ba657371fdcea98a631fa1363f8 @rtyler committed Mar 22, 2010
Showing with 31 additions and 1 deletion.
  1. +11 −1 encoder.c
  2. +20 −0 tests/unit.py
View
@@ -126,7 +126,17 @@ static yajl_gen_status ProcessObject(_YajlEncoder *self, PyObject *object)
status = yajl_gen_map_open(handle);
while (PyDict_Next(object, &position, &key, &value)) {
- status = ProcessObject(self, key);
+ PyObject *newKey = key;
+
+ if ( (PyFloat_Check(key)) ||
+#ifndef IS_PYTHON3
+ (PyInt_Check(key)) ||
+#endif
+ (PyLong_Check(key)) ) {
+ newKey = PyObject_Unicode(key);
+ }
+
+ status = ProcessObject(self, newKey);
status = ProcessObject(self, value);
}
return yajl_gen_map_close(handle);
View
@@ -220,6 +220,26 @@ def testSets(self):
''' http://github.com/rtyler/py-yajl/issues#issue/9 '''
self.failUnlessRaises(TypeError, yajl.dumps, set([2,3]))
+
+class IssueTenTest(unittest.TestCase):
+ def testInt(self):
+ ''' http://github.com/rtyler/py-yajl/issues#issue/10 '''
+ data = {1 : 2}
+ result = yajl.loads(yajl.dumps(data))
+ self.assertEquals({'1': 2}, result)
+
+ def testFloat(self):
+ ''' http://github.com/rtyler/py-yajl/issues#issue/10 '''
+ data = {1.2 : 2}
+ result = yajl.loads(yajl.dumps(data))
+ self.assertEquals({'1.2': 2}, result)
+
+ def testLong(self):
+ ''' http://github.com/rtyler/py-yajl/issues#issue/10 '''
+ data = {long(1) : 2}
+ result = yajl.loads(yajl.dumps(data))
+ self.assertEquals({'1': 2}, result)
+
if __name__ == '__main__':
verbosity = '-v' in sys.argv and 2 or 1
runner = unittest.TextTestRunner(verbosity=verbosity)

0 comments on commit f40427c

Please sign in to comment.