def test_(self): self.assertEqual(r'"Quote \" in text"', to_js_string('Quote " in text')) self.assertEqual(r'''"\\\"\b\f\n\r\t'"''', to_js_string('\\"\b\f\n\r\t\'')) self.assertEqual(r'"\u0002\u001e"', to_js_string('\x02\x1e')) self.assertEqual(r'"\u0026\u003c\u003e"', to_js_string('&<>'))
def test_(self): self.assertEqual(r'"Quote \" in text"', to_js_string('Quote " in text')) self.assertEqual(r'''"\\\"\b\f\n\r\t'"''', to_js_string("\\\"\b\f\n\r\t'")) self.assertEqual(r'"\u0002\u001e"', to_js_string("\x02\x1e")) self.assertEqual(r'"\u0026\u003c\u003e"', to_js_string("&<>")) self.assertEqual('""', to_js_string("")) self.assertEqual('""', to_js_string(None))
def to_json(value): """Encode `value` to JSON.""" if isinstance(value, basestring): return to_js_string(value) elif value is None: return "null" elif value is False: return "false" elif value is True: return "true" elif isinstance(value, (int, long)): return str(value) elif isinstance(value, float): return repr(value) elif isinstance(value, (list, tuple)): return "[%s]" % ",".join(to_json(each) for each in value) elif isinstance(value, dict): return "{%s}" % ",".join("%s:%s" % (to_json(k), to_json(v)) for k, v in sorted(value.iteritems())) else: raise TypeError("Cannot encode type %s" % value.__class__.__name__)
def to_json(value): """Encode `value` to JSON.""" if isinstance(value, basestring): return to_js_string(value) elif value is None: return 'null' elif value is False: return 'false' elif value is True: return 'true' elif isinstance(value, (int, long)): return str(value) elif isinstance(value, float): return repr(value) elif isinstance(value, (list, tuple)): return '[%s]' % ','.join(to_json(each) for each in value) elif isinstance(value, dict): return '{%s}' % ','.join('%s:%s' % (to_json(k), to_json(v)) for k, v in sorted(value.iteritems())) else: raise TypeError('Cannot encode type %s' % value.__class__.__name__)