| 1506 | #### JSON PARSER ################################################################################### |
| 1507 | |
| 1508 | class JSON(object): |
| 1509 | |
| 1510 | def __init__(self): |
| 1511 | self.float = lambda f: ("%.3f" % f).rstrip("0") |
| 1512 | |
| 1513 | def __call__(self, obj, *args, **kwargs): |
| 1514 | """ Returns a JSON string from the given data. |
| 1515 | The data can be a nested structure of dict, list, str, unicode, bool, int, float and None. |
| 1516 | """ |
| 1517 | def _str(obj): |
| 1518 | if isinstance(obj, type(None)): |
| 1519 | return "null" |
| 1520 | if isinstance(obj, bool): |
| 1521 | return obj and "true" or "false" |
| 1522 | if isinstance(obj, (int, long)): # Also validates bools, so those are handled first. |
| 1523 | return str(obj) |
| 1524 | if isinstance(obj, float): |
| 1525 | return str(self.float(obj)) |
| 1526 | if isinstance(obj, (str, unicode)): |
| 1527 | return '"%s"' % obj.replace('"', '\\"') |
| 1528 | if isinstance(obj, dict): |
| 1529 | return "{%s}" % ", ".join(['"%s": %s' % (k.replace('"', '\\"'), _str(v)) for k, v in obj.items()]) |
| 1530 | if isinstance(obj, (list, tuple, GeneratorType)): |
| 1531 | return "[%s]" % ", ".join(_str(v) for v in obj) |
| 1532 | raise TypeError, "can't process %s." % type(obj) |
| 1533 | return "%s" % _str(obj) |
| 1534 | |
| 1535 | json = JSON() |
| 1536 |
no outgoing calls
no test coverage detected
searching dependent graphs…