Skip to content

Commit 31eb8e2

Browse files
author
Kenneth Reitz
committed
omnijson
1 parent 2e743c7 commit 31eb8e2

File tree

8 files changed

+1657
-0
lines changed

8 files changed

+1657
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from __future__ import absolute_import
4+
5+
from .core import loads, dumps, JSONError
6+
7+
8+
__all__ = ('loads', 'dumps', 'JSONError')
9+
10+
11+
__version__ = '0.1.2'
12+
__author__ = 'Kenneth Reitz'
13+
__license__ = 'MIT'

github3/packages/omnijson/core.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# -*- coding: utf-8 -*-
2+
3+
"""
4+
omijson.core
5+
~~~~~~~~~~~~
6+
7+
This module provides the core omnijson functionality.
8+
9+
"""
10+
11+
import sys
12+
13+
engine = None
14+
_engine = None
15+
16+
17+
options = [
18+
['ujson', 'loads', 'dumps', (ValueError,)],
19+
['yajl', 'loads', 'dumps', (TypeError, ValueError)],
20+
['jsonlib2', 'read', 'write', (ValueError,)],
21+
['jsonlib', 'read', 'write', (ValueError,)],
22+
['simplejson', 'loads', 'dumps', (TypeError, ValueError)],
23+
['json', 'loads', 'dumps', (TypeError, ValueError)],
24+
['simplejson_from_packages', 'loads', 'dumps', (ValueError,)],
25+
]
26+
27+
28+
def _import(engine):
29+
try:
30+
if '_from_' in engine:
31+
engine, package = engine.split('_from_')
32+
m = __import__(package, globals(), locals(), [engine], -1)
33+
return getattr(m, engine)
34+
35+
return __import__(engine)
36+
37+
except ImportError:
38+
return False
39+
40+
41+
def loads(s, **kwargs):
42+
"""Loads JSON object."""
43+
44+
try:
45+
return _engine[0](s)
46+
47+
except:
48+
# crazy 2/3 exception hack
49+
# http://www.voidspace.org.uk/python/weblog/arch_d7_2010_03_20.shtml
50+
51+
ExceptionClass, why = sys.exc_info()[:2]
52+
53+
if any([(issubclass(ExceptionClass, e)) for e in _engine[2]]):
54+
raise JSONError(why)
55+
else:
56+
raise why
57+
58+
59+
def dumps(o, **kwargs):
60+
"""Dumps JSON object."""
61+
62+
try:
63+
return _engine[1](o)
64+
65+
except:
66+
ExceptionClass, why = sys.exc_info()[:2]
67+
68+
if any([(issubclass(ExceptionClass, e)) for e in _engine[2]]):
69+
raise JSONError(why)
70+
else:
71+
raise why
72+
73+
74+
class JSONError(ValueError):
75+
"""JSON Failed."""
76+
77+
78+
# ------
79+
# Magic!
80+
# ------
81+
82+
83+
for e in options:
84+
85+
__engine = _import(e[0])
86+
87+
if __engine:
88+
engine, _engine = e[0], e[1:4]
89+
90+
for i in (0, 1):
91+
_engine[i] = getattr(__engine, _engine[i])
92+
93+
break

github3/packages/omnijson/packages/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)