diff --git a/README.rst b/README.rst index 31bb096a83c83733e3e9ab477d0ee91019d5a9e9..19293ab61cc3652d2bef30c95559a7c2bc88cd5f 100644 --- a/README.rst +++ b/README.rst @@ -78,7 +78,7 @@ at: https://www.shore.co.il/git/. TODO ---- -- Add unit tests of filters using doctest. +- Fix unicode strings in Python 2.7 only doctests in :code:`load_json`. - Fix combining dictionaries test. - Fix Travis CI test on Python 3.2 (https://travis-ci.org/adarnimrod/template/jobs/187388235). - Release on tagged commits to PyPI in Travis CI diff --git a/template/filters.py b/template/filters.py index 993435afa6ee1a96ef97e15a8d1e3c2b9d1a5f90..72669216d124e6cb8c0a8512928d835c1211285b 100644 --- a/template/filters.py +++ b/template/filters.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import (absolute_import, division, + print_function, unicode_literals) def to_yaml(value): @@ -20,16 +22,51 @@ def to_yaml(value): def to_json(value): + ''' + Converts given data structure to JSON form. + Examples: + + >>> to_json([1,2,3]) + '[1, 2, 3]' + >>> to_json({'b':2}) + '{"b": 2}' + >>> to_json(2) + '2' + >>> to_json({1: {'a': [1,2,3]}}) + '{"1": {"a": [1, 2, 3]}}' + ''' from json import dumps return dumps(value) def from_json(value): + ''' + Returns native data structure from the given JSON string. + Examples: + + >>> from_json('[1, 2, 3]') + [1, 2, 3] + >>> from_json('"a"') + u'a' + >>> from_json('{"1": {"a": [1, 2, 3]}}') + {u'1': {u'a': [1, 2, 3]}} + ''' from json import loads return loads(value) def from_yaml(value): + ''' + Returns native data structure from the given YAML string. + Examples: + + >>> from_yaml('a') + 'a' + >>> from_yaml('[1, 2, 3]') + [1, 2, 3] + >>> from_yaml('{"1": {"a": [1, 2, 3]}}') + {'1': {'a': [1, 2, 3]}} + ''' from yaml import safe_load return safe_load(value)