mirror of
https://github.com/kennethreitz/tablib.git
synced 2026-06-05 23:10:17 +00:00
Fix: Circular reference detected error (#332)
* Rename function name * Add uuid handler on json dumps * Add myself to authors
This commit is contained in:
committed by
Iuri de Silvio
parent
38486231cc
commit
3d5943a8a4
@@ -34,3 +34,4 @@ Patches and Suggestions
|
||||
- Mathias Loesch
|
||||
- Tushar Makkar
|
||||
- Andrii Soldatenko
|
||||
- Bruno Soares
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
""" Tablib - JSON Support
|
||||
"""
|
||||
import decimal
|
||||
from uuid import UUID
|
||||
|
||||
import tablib
|
||||
|
||||
@@ -15,24 +16,23 @@ title = 'json'
|
||||
extensions = ('json', 'jsn')
|
||||
|
||||
|
||||
def date_handler(obj):
|
||||
if isinstance(obj, decimal.Decimal):
|
||||
def serialize_objects_handler(obj):
|
||||
if isinstance(obj, decimal.Decimal) or isinstance(obj, UUID):
|
||||
return str(obj)
|
||||
elif hasattr(obj, 'isoformat'):
|
||||
return obj.isoformat()
|
||||
else:
|
||||
return obj
|
||||
# return obj.isoformat() if hasattr(obj, 'isoformat') else obj
|
||||
|
||||
|
||||
def export_set(dataset):
|
||||
"""Returns JSON representation of Dataset."""
|
||||
return json.dumps(dataset.dict, default=date_handler)
|
||||
return json.dumps(dataset.dict, default=serialize_objects_handler)
|
||||
|
||||
|
||||
def export_book(databook):
|
||||
"""Returns JSON representation of Databook."""
|
||||
return json.dumps(databook._package(), default=date_handler)
|
||||
return json.dumps(databook._package(), default=serialize_objects_handler)
|
||||
|
||||
|
||||
def import_set(dset, in_stream):
|
||||
|
||||
@@ -6,6 +6,7 @@ import doctest
|
||||
import json
|
||||
import unittest
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
import datetime
|
||||
|
||||
@@ -226,6 +227,22 @@ class TablibTestCase(unittest.TestCase):
|
||||
|
||||
# Delete from invalid index
|
||||
self.assertRaises(IndexError, self.founders.__delitem__, 3)
|
||||
|
||||
def test_json_export(self):
|
||||
"""Verify exporting dataset object as JSON"""
|
||||
|
||||
address_id = uuid4()
|
||||
headers = self.headers + ('address_id',)
|
||||
founders = tablib.Dataset(headers=headers, title='Founders')
|
||||
founders.append(('John', 'Adams', 90, address_id))
|
||||
founders_json = founders.export('json')
|
||||
|
||||
expected_json = (
|
||||
'[{"first_name": "John", "last_name": "Adams", "gpa": 90, '
|
||||
'"address_id": "%s"}]' % str(address_id)
|
||||
)
|
||||
|
||||
self.assertEqual(founders_json, expected_json)
|
||||
|
||||
def test_csv_export(self):
|
||||
"""Verify exporting dataset object as CSV."""
|
||||
|
||||
Reference in New Issue
Block a user