Package Products :: Package ZenUtils :: Module json |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenUtils.json

     1  ###########################################################################
     2  #
     3  # This program is part of Zenoss Core, an open source monitoring platform.
     4  # Copyright (C) 2007, Zenoss Inc.
     5  #
     6  # This program is free software; you can redistribute it and/or modify it
     7  # under the terms of the GNU General Public License version 2 as published by
     8  # the Free Software Foundation.
     9  #
    10  # For complete information please visit: http://www.zenoss.com/oss/
    11  #
    12  ###########################################################################
    13
    14  import simplejson
    15
    16 -def json(value):
    17      """
    18      Serialize C{value} into a JSON string.
    19
    20      If C{value} is callable, a decorated version of C{value} that serializes its
    21      return value will be returned.
    22
    23          >>> value = (dict(a=1L), u"123", 123)
    24          >>> print json(value)
    25          [{"a": 1}, "123", 123]
    26          >>> @json
    27          ... def f():
    28          ...     return value
    29          ...
    30          >>> print f()
    31          [{"a": 1}, "123", 123]
    32
    33      @param value: An object to be serialized
    34      @type value: dict, list, tuple, str, etc. or callable
    35      @return: The JSON representation of C{value} or a decorated function
    36      @rtype: str, func
    37      """
    38      if callable(value):
    39          # Decorate the given callable
    40          def inner(*args, **kwargs):
    41              return simplejson.dumps(value(*args, **kwargs))
    42          # Well-behaved decorators look like the decorated function
    43          inner.__name__ = value.__name__
    44          inner.__dict__.update(value.__dict__)
    45          inner.__doc__ = value.__doc__
    46          return inner
    47      else:
    48          # Simply serialize the value passed
    49          return simplejson.dumps(value)
    50
    51 -def unjson(value):
    52      """
    53      Create the Python object represented by the JSON string C{value}.
    54
    55          >>> jsonstr = '[{"a": 1}, "123", 123]'
    56          >>> print unjson(jsonstr)
    57          [{'a': 1}, '123', 123]
    58
    59      @param value: A JSON string
    60      @type value: str
    61      @return: The object represented by C{value}
    62      """
    63      return simplejson.loads(value)
    64