aboutsummaryrefslogtreecommitdiffstats
path: root/github3/packages/omnijson/core.py
diff options
context:
space:
mode:
authorKenneth Reitz <me@kennethreitz.com>2011-07-24 18:13:35 -0400
committerKenneth Reitz <me@kennethreitz.com>2011-07-24 18:13:35 -0400
commit31eb8e2e51ae4c3bb0efe92122d1a618cedced31 (patch)
tree718a731626f5f271d8d7d8068ec053891416ba93 /github3/packages/omnijson/core.py
parentno reason to be not-authed (diff)
downloadpython-github3-31eb8e2e51ae4c3bb0efe92122d1a618cedced31.tar.xz
python-github3-31eb8e2e51ae4c3bb0efe92122d1a618cedced31.zip
omnijson
Diffstat (limited to 'github3/packages/omnijson/core.py')
-rw-r--r--github3/packages/omnijson/core.py93
1 files changed, 93 insertions, 0 deletions
diff --git a/github3/packages/omnijson/core.py b/github3/packages/omnijson/core.py
new file mode 100644
index 0000000..8b49537
--- /dev/null
+++ b/github3/packages/omnijson/core.py
@@ -0,0 +1,93 @@
+# -*- coding: utf-8 -*-
+
+"""
+omijson.core
+~~~~~~~~~~~~
+
+This module provides the core omnijson functionality.
+
+"""
+
+import sys
+
+engine = None
+_engine = None
+
+
+options = [
+ ['ujson', 'loads', 'dumps', (ValueError,)],
+ ['yajl', 'loads', 'dumps', (TypeError, ValueError)],
+ ['jsonlib2', 'read', 'write', (ValueError,)],
+ ['jsonlib', 'read', 'write', (ValueError,)],
+ ['simplejson', 'loads', 'dumps', (TypeError, ValueError)],
+ ['json', 'loads', 'dumps', (TypeError, ValueError)],
+ ['simplejson_from_packages', 'loads', 'dumps', (ValueError,)],
+]
+
+
+def _import(engine):
+ try:
+ if '_from_' in engine:
+ engine, package = engine.split('_from_')
+ m = __import__(package, globals(), locals(), [engine], -1)
+ return getattr(m, engine)
+
+ return __import__(engine)
+
+ except ImportError:
+ return False
+
+
+def loads(s, **kwargs):
+ """Loads JSON object."""
+
+ try:
+ return _engine[0](s)
+
+ except:
+ # crazy 2/3 exception hack
+ # http://www.voidspace.org.uk/python/weblog/arch_d7_2010_03_20.shtml
+
+ ExceptionClass, why = sys.exc_info()[:2]
+
+ if any([(issubclass(ExceptionClass, e)) for e in _engine[2]]):
+ raise JSONError(why)
+ else:
+ raise why
+
+
+def dumps(o, **kwargs):
+ """Dumps JSON object."""
+
+ try:
+ return _engine[1](o)
+
+ except:
+ ExceptionClass, why = sys.exc_info()[:2]
+
+ if any([(issubclass(ExceptionClass, e)) for e in _engine[2]]):
+ raise JSONError(why)
+ else:
+ raise why
+
+
+class JSONError(ValueError):
+ """JSON Failed."""
+
+
+# ------
+# Magic!
+# ------
+
+
+for e in options:
+
+ __engine = _import(e[0])
+
+ if __engine:
+ engine, _engine = e[0], e[1:4]
+
+ for i in (0, 1):
+ _engine[i] = getattr(__engine, _engine[i])
+
+ break