Edgewall Software

source: trunk/bitten/util/json.py @ 1001

Last change on this file since 1001 was 859, checked in by dfraser, 14 years ago

Added re import (required for worst-case fallback) - see #426

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/python-source
File size: 3.3 KB
CovLine 
1# -*- coding: utf-8 -*-
2#
3# Copyright (C)2006-2009 Edgewall Software
4# Copyright (C) 2006 Christopher Lenz <cmlenz@gmx.de>
5# All rights reserved.
6#
7# This software is licensed as described in the file COPYING, which
8# you should have received as part of this distribution. The terms
9# are also available at http://trac.edgewall.org/wiki/TracLicense.
10#
11# This software consists of voluntary contributions made by many
12# individuals. For the exact contribution history, see the revision
13# history and logs, available at http://trac.edgewall.org/log/.
14
115"""Utility functions for converting to web formats"""
16
17# to_json is really a wrapper for trac.util.presentation.to_json, but we have lots of fallbacks for compatibility
18# trac.util.presentation.to_json is present from Trac 0.12
19# If that's not present, we fall back to the default Python json module, present from Python 2.6 onwards
20# If that's not present, we have a copy of the to_json method, which we will remove once Trac 0.11 support is removed
21# And finally, the to_json method requires trac.util.text.javascript_quote, which is only present from Trac 0.11.3, so we have a copy of that too
22
123import re
24
125try:
26    # to_json is present from Trac 0.12 onwards - should remove once Trac 0.11 support is removed
127    from trac.util.presentation import to_json
028except ImportError:
029    try:
30        # If we have Python 2.6 onwards, use the json method directly
031        from json import dumps
32       
033        def to_json(value):
34            """Encode `value` to JSON."""
035            return dumps(value, sort_keys=True, separators=(',', ':'))
036    except ImportError:
37        # javascript_quote is present from Trac 0.11.3 onwards - should remove once Trac 0.11.2 support is removed
038        try:
039            from trac.util.text import javascript_quote
040        except ImportError:
041            _js_quote = {'\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f',
042                 '\n': '\\n', '\r': '\\r', '\t': '\\t', "'": "\\'"}
043            for i in range(0x20):
044                _js_quote.setdefault(chr(i), '\\u%04x' % i)
045            _js_quote_re = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t\']')
046            def javascript_quote(text):
47                """Quote strings for inclusion in javascript"""
048                if not text:
049                    return ''
050                def replace(match):
051                    return _js_quote[match.group(0)]
052                return _js_quote_re.sub(replace, text)
53
054        def to_json(value):
55            """Encode `value` to JSON."""
056            if isinstance(value, basestring):
057                return '"%s"' % javascript_quote(value)
058            elif value is None:
059                return 'null'
060            elif value is False:
061                return 'false'
062            elif value is True:
063                return 'true'
064            elif isinstance(value, (int, long)):
065                return str(value)
066            elif isinstance(value, float):
067                return repr(value)
068            elif isinstance(value, (list, tuple)):
069                return '[%s]' % ','.join(to_json(each) for each in value)
070            elif isinstance(value, dict):
071                return '{%s}' % ','.join('%s:%s' % (to_json(k), to_json(v))
072                                         for k, v in sorted(value.iteritems()))
073            else:
074                raise TypeError('Cannot encode type %s' % value.__class__.__name__)
Note: See TracBrowser for help on using the repository browser.