diff options
author | Marko Kreen | 2010-09-23 00:52:39 +0000 |
---|---|---|
committer | Marko Kreen | 2010-09-23 00:54:03 +0000 |
commit | e9e68b6f19a710b02c89c1d7a80d5ef752a0460f (patch) | |
tree | c464c7da5f332d46c5c421c064b8d45b8a0a3188 | |
parent | 020cdb4dc4c2dd8137dfbb66daab4a0793b91dd9 (diff) |
skytools: JSON wrapper
- find working JSON module
- easier kwargs API
-rw-r--r-- | python/skytools/quoting.py | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/python/skytools/quoting.py b/python/skytools/quoting.py index e83d2495..e46f42dd 100644 --- a/python/skytools/quoting.py +++ b/python/skytools/quoting.py @@ -13,6 +13,7 @@ __all__ = [ "quote_bytea_literal", "quote_bytea_copy", "quote_statement", "quote_ident", "quote_fqident", "quote_json", "unescape_copy", "unquote_ident", "unquote_fqident", + "json_encode", "json_decode", ] try: @@ -145,6 +146,39 @@ def unquote_fqident(val): tmp = val.split('.', 1) return "%s.%s" % (unquote_ident(tmp[0]), unquote_ident(tmp[1])) +# accept simplejson or py2.6+ json module +# search for simplejson first as there exists +# incompat 'json' module +try: + import simplejson as json +except ImportError: + try: + import json + except: + pass + +def json_encode(val = None, **kwargs): + """Creates JSON string from Python object. + + >>> json_encode({'a': 1}) + '{"a": 1}' + >>> json_encode('a') + '"a"' + >>> json_encode(['a']) + '["a"]' + >>> json_encode(a=1) + '{"a": 1}' + """ + return json.dumps(val or kwargs) + +def json_decode(s): + """Parses JSON string into Python object. + + >>> json_decode('[1]') + [1] + """ + return json.loads(s) + if __name__ == '__main__': import doctest doctest.testmod() |