Commit f03dd13a by Fred Smith
parents 9b0eca4a cc485f03
*.egg-info
*.pyc
*.pyo
.DS_Store
build
dist
MANIFEST
test/example/*.sqlite3
doc/.build
distribute-*.egg
distribute-*.tar.gz
========
Examples
========
This file enumerates some common patterns for working with jsonpipe output. The
examples here use the file ``example.json``, which can be found in the root of
this repo. Basic familiarity with the UNIX shell, common utilities and regular
expressions is assumed.
Simple Selection
================
In Python::
>>> json[12]['user']['screen_name']
u"ManiacasCarlos"
On the command-line, just grep for the specific path you're looking for::
$ jsonpipe < example.json | grep -P '^/12/user/screen_name\t'
/12/user/screen_name "ManiacasCarlos"
The pattern used here is terminated with ``\t``, because otherwise we'd get
sub-components of the ``screen_name`` path if it were an object, and we'd also
pick up any keys which started with the string ``screen_name`` (so we might get
``screen_name_123`` and ``screen_name_abc`` if those keys existed).
Extracting Entire Objects
=========================
In Python::
>>> json[12]['user']
{... u'screen_name': u'ManiacasCarlos', ...}
On the command-line, grep for the path again but terminate with ``/`` instead
of ``\t``::
$ jsonpipe < example.json | grep -P '^/12/user/'
...
/12/user/profile_use_background_image true
/12/user/protected false
/12/user/screen_name "ManiacasCarlos"
/12/user/show_all_inline_media false
...
You can also filter for either a simple value *or* an entire object by
terminating the pattern with a character range::
$ jsonpipe < example.json | grep -P '^/12/user[/\t]'
/12/user {}
/12/user/contributors_enabled false
/12/user/created_at "Mon Jan 31 20:42:31 +0000 2011"
/12/user/default_profile false
...
Searching Based on Equality or Patterns
=======================================
Find users with a screen name beginning with a lowercase 'm'::
$ jsonpipe < example.json | grep -P '/user/screen_name\t"m'
/0/user/screen_name "milenemagnus_"
/11/user/screen_name "mommiepreneur"
/14/user/screen_name "mantegavoadora"
include distribute_setup.py
========
jsonpipe
========
Everyone I know prefers to work with JSON over XML, but sadly there is a sore
lack of utilities of the quality or depth of `html-xml-utils`_ and
`XMLStarlet`_ for actually processing JSON data in an automated fashion, short
of writing an *ad hoc* processor in your favourite programming language.
.. _html-xml-utils: http://www.w3.org/Tools/HTML-XML-utils/README
.. _XMLStarlet: http://xmlstar.sourceforge.net/
**jsonpipe** is a step towards a solution: it traverses a JSON object and
produces a simple, line-based textual format which can be processed by all your
UNIX favourites like grep, sed, awk, cut and diff. It may also be valuable
within programming languages---in fact, it was originally conceived as a way of
writing simple test assertions against JSON output without coupling the tests
too closely to the specific structure used.
This implementation (which should be considered the reference) is written in
Python.
Example
=======
A ``<pre>`` is worth a thousand words. For simple JSON values::
$ echo '"Hello, World!"' | jsonpipe
/ "Hello, World!"
$ echo 123 | jsonpipe
/ 123
$ echo 0.25 | jsonpipe
/ 0.25
$ echo null | jsonpipe
/ null
$ echo true | jsonpipe
/ true
$ echo false | jsonpipe
/ false
The 'root' of the object tree is represented by a single ``/`` character, and
for simple values it doesn't get any more complex than the above. Note that a
single tab character separates the path on the left from the literal value on
the right.
Composite data structures use a hierarchical syntax, where individual
keys/indices are children of the path to the containing object::
$ echo '{"a": 1, "b": 2}' | jsonpipe
/ {}
/a 1
/b 2
$ echo '["foo", "bar", "baz"]' | jsonpipe
/ []
/0 "foo"
/1 "bar"
/2 "baz"
For an object or array, the right-hand column indicates the datatype, and will
be either ``{}`` (object) or ``[]`` (array). For objects, the order of the keys
is preserved in the output.
The path syntax allows arbitrarily complex data structures::
$ echo '[{"a": [{"b": {"c": ["foo"]}}]}]' | jsonpipe
/ []
/0 {}
/0/a []
/0/a/0 {}
/0/a/0/b {}
/0/a/0/b/c []
/0/a/0/b/c/0 "foo"
Caveat: Path Separators
=======================
Because the path components are separated by ``/`` characters, an object key
like ``"abc/def"`` would result in ambiguous output. jsonpipe will throw
an error if this occurs in your input, so that you can recognize and handle the
issue. To mitigate the problem, you can choose a different path separator::
$ echo '{"abc/def": 123}' | jsonpipe -s '☃'
☃ {}
☃abc/def 123
The Unicode snowman is chosen here because it's unlikely to occur as part of
the key in most JSON objects, but any character or string (e.g. ``:``, ``::``,
``~``) will do.
jsonunpipe
==========
Another useful part of the library is ``jsonunpipe``, which turns jsonpipe
output back into JSON proper::
$ echo '{"a": 1, "b": 2}' | jsonpipe | jsonunpipe
{"a": 1, "b": 2}
jsonunpipe also supports incomplete information (such as you might get from
grep), and will assume all previously-undeclared parts of a path to be JSON
objects::
$ echo "/a/b/c 123" | jsonunpipe
{"a": {"b": {"c": 123}}}
Python API
==========
Since jsonpipe is written in Python, you can import it and use it without
having to spawn another process::
>>> from jsonpipe import jsonpipe
>>> for line in jsonpipe({"a": 1, "b": 2}):
... print line
/ {}
/a 1
/b 2
Note that the ``jsonpipe()`` generator function takes a Python object, not a
JSON string, so the order of dictionary keys may be slightly unpredictable in
the output. You can use ``simplejson.OrderedDict`` to get a fixed ordering::
>>> from simplejson import OrderedDict
>>> obj = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> obj
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> for line in jsonpipe(obj):
... print line
/ {}
/a 1
/b 2
/c 3
A more general hint: if you need to parse JSON but maintain ordering for object
keys, use the ``object_pairs_hook`` option on ``simplejson.load(s)``::
>>> import simplejson
>>> simplejson.loads('{"a": 1, "b": 2, "c": 3}',
... object_pairs_hook=simplejson.OrderedDict)
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
Of course, a Python implementation of jsonunpipe also exists::
>>> from jsonpipe import jsonunpipe
>>> jsonunpipe(['/\t{}', '/a\t123'])
{'a': 123}
You can pass a ``decoder`` parameter, as in the following example, where the
JSON object returned uses an ordered dictionary::
>>> jsonunpipe(['/\t{}', '/a\t123', '/b\t456'],
... decoder=simplejson.JSONDecoder(
... object_pairs_hook=simplejson.OrderedDict))
OrderedDict([('a', 123), ('b', 456)])
Installation
============
**jsonpipe** is written in Python, so is best installed using ``pip``::
pip install jsonpipe
Note that it requires Python v2.5 or later (simplejson only supports 2.5+).
(Un)license
===========
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
This diff is collapsed. Click to expand it.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distribute_setup import use_setuptools
use_setuptools()
import re
from setuptools import setup, find_packages
import os.path as p
def get_version():
source = open(p.join(p.dirname(p.abspath(__file__)),
'src', 'jsonpipe', '__init__.py')).read()
match = re.search(r'__version__\s*=\s*[\'"]([^\'"]+)[\'"]', source)
if not match:
raise RuntimeError("Couldn't find the version string in src/jsonpipe/__init__.py")
return match.group(1)
setup(
name='jsonpipe',
version=get_version(),
description="Convert JSON to a UNIX-friendly line-based format.",
author='Zachary Voase',
author_email='z@dvxhouse.com',
url='http://github.com/dvxhouse/jsonpipe',
package_dir={'': 'src'},
packages=find_packages(where='src'),
entry_points={'console_scripts': ['jsonpipe = jsonpipe:main',
'jsonunpipe = jsonpipe:main_unpipe']},
install_requires=['simplejson>=2.1.3', 'argparse>=1.1', 'calabash==0.0.3'],
test_suite='jsonpipe._get_tests',
)
# -*- coding: utf-8 -*-
import sys
import argparse
import simplejson
from pipe import jsonpipe, jsonunpipe
__all__ = ['jsonpipe', 'jsonunpipe']
__version__ = '0.0.8'
def _get_tests():
import doctest
import inspect
import sys
import unittest
import jsonpipe.sh
def _from_module(module, object):
"""Backported fix for http://bugs.python.org/issue1108."""
if module is None:
return True
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
finder = doctest.DocTestFinder()
finder._from_module = _from_module
suite = unittest.TestSuite()
for name, module in sys.modules.iteritems():
if name.startswith('jsonpipe'):
try:
mod_suite = doctest.DocTestSuite(
module, test_finder=finder,
optionflags=(doctest.NORMALIZE_WHITESPACE |
doctest.ELLIPSIS))
except ValueError:
continue
suite.addTests(mod_suite)
return suite
PARSER = argparse.ArgumentParser()
PARSER.add_argument('-s', '--separator', metavar='SEP', default='/',
help="Set a custom path component separator (default: /)")
PARSER.add_argument('-v', '--version', action='version',
version='%%(prog)s v%s' % (__version__,))
def main():
args = PARSER.parse_args()
# Load JSON from stdin, preserving the order of object keys.
json_obj = simplejson.load(sys.stdin,
object_pairs_hook=simplejson.OrderedDict)
for line in jsonpipe(json_obj, pathsep=args.separator):
print line
def main_unpipe():
args = PARSER.parse_args()
simplejson.dump(
jsonunpipe(iter(sys.stdin), pathsep=args.separator,
decoder=simplejson.JSONDecoder(
object_pairs_hook=simplejson.OrderedDict)),
sys.stdout)
import simplejson
__all__ = ['jsonpipe', 'jsonunpipe']
def jsonpipe(obj, pathsep='/', path=()):
r"""
Generate a jsonpipe stream for the provided (parsed) JSON object.
This generator will yield output as UTF-8-encoded bytestrings line-by-line.
These lines will *not* be terminated with line ending characters.
The provided object can be as complex as you like, but it must consist only
of:
* Dictionaries (or subclasses of `dict`)
* Lists or tuples (or subclasses of the built-in types)
* Unicode Strings (`unicode`, utf-8 encoded `str`)
* Numbers (`int`, `long`, `float`)
* Booleans (`True`, `False`)
* `None`
Please note that, where applicable, *all* input must use either native
Unicode strings or UTF-8-encoded bytestrings, and all output will be UTF-8
encoded.
The simplest case is outputting JSON values (strings, numbers, booleans and
nulls):
>>> def pipe(obj): # Shim for easier demonstration.
... print '\n'.join(jsonpipe(obj))
>>> pipe(u"Hello, World!")
/ "Hello, World!"
>>> pipe(123)
/ 123
>>> pipe(0.25)
/ 0.25
>>> pipe(None)
/ null
>>> pipe(True)
/ true
>>> pipe(False)
/ false
jsonpipe always uses '/' to represent the top-level object. Dictionaries
are displayed as ``{}``, with each key shown as a sub-path:
>>> pipe({"a": 1, "b": 2})
/ {}
/a 1
/b 2
Lists are treated in much the same way, only the integer indices are used
as the keys, and the top-level list object is shown as ``[]``:
>>> pipe([1, "foo", 2, "bar"])
/ []
/0 1
/1 "foo"
/2 2
/3 "bar"
Finally, the practical benefit of using hierarchical paths is that the
syntax supports nesting of arbitrarily complex constructs:
>>> pipe([{"a": [{"b": {"c": ["foo"]}}]}])
/ []
/0 {}
/0/a []
/0/a/0 {}
/0/a/0/b {}
/0/a/0/b/c []
/0/a/0/b/c/0 "foo"
Because the sole separator of path components is a ``/`` character by
default, keys containing this character would result in ambiguous output.
Therefore, if you try to write a dictionary with a key containing the path
separator, :func:`jsonpipe` will raise a :exc:`ValueError`:
>>> pipe({"a/b": 1})
Traceback (most recent call last):
...
ValueError: Path separator '/' present in key 'a/b'
In more complex examples, some output may be written before the exception
is raised. To mitigate this problem, you can provide a custom path
separator:
>>> print '\n'.join(jsonpipe({"a/b": 1}, pathsep=':'))
: {}
:a/b 1
The path separator should be a bytestring, and you are advised to use
something you are almost certain will not be present in your dictionary
keys.
"""
def output(string):
return pathsep + pathsep.join(path) + "\t" + string
if is_value(obj):
yield output(simplejson.dumps(obj))
raise StopIteration # Stop the generator immediately.
elif isinstance(obj, dict):
yield output('{}')
iterator = obj.iteritems()
elif hasattr(obj, '__iter__'):
yield output('[]')
iterator = enumerate(obj)
else:
raise TypeError("Unsupported type for jsonpipe output: %r" %
type(obj))
for key, value in iterator:
# Check the key for sanity.
key = to_str(key)
if pathsep in key:
# In almost any case this is not what the user wants; having
# the path separator in the key would create ambiguous output
# so we should fail loudly and as quickly as possible.
raise ValueError("Path separator %r present in key %r" %
(pathsep, key))
for line in jsonpipe(value, pathsep=pathsep, path=path + (key,)):
yield line
def jsonunpipe(lines, pathsep='/', discard='',
decoder=simplejson._default_decoder):
r"""
Parse a stream of jsonpipe output back into a JSON object.
>>> def unpipe(s): # Shim for easier demonstration.
... print repr(jsonunpipe(s.strip().splitlines()))
Works as expected for simple JSON values::
>>> unpipe('/\t"abc"')
'abc'
>>> unpipe('/\t123')
123
>>> unpipe('/\t0.25')
0.25
>>> unpipe('/\tnull')
None
>>> unpipe('/\ttrue')
True
>>> unpipe('/\tfalse')
False
And likewise for more complex objects::
>>> unpipe('''
... /\t{}
... /a\t1
... /b\t2''')
{'a': 1, 'b': 2}
>>> unpipe('''
... /\t[]
... /0\t{}
... /0/a\t[]
... /0/a/0\t{}
... /0/a/0/b\t{}
... /0/a/0/b/c\t[]
... /0/a/0/b/c/0\t"foo"''')
[{'a': [{'b': {'c': ['foo']}}]}]
Any level in the path left unspecified will be assumed to be an object::
>>> unpipe('''
... /a/b/c\t123''')
{'a': {'b': {'c': 123}}}
"""
def parse_line(line):
path, json = line.rstrip().split('\t')
return path.split(pathsep)[1:], decoder.decode(json)
def getitem(obj, index):
if isinstance(obj, (list, tuple)):
return obj[int(index)]
# All non-existent keys are assumed to be an object.
if index not in obj:
obj[index] = decoder.decode('{}')
return obj[index]
def setitem(obj, index, value):
if isinstance(obj, list):
index = int(index)
if len(obj) == index:
obj.append(value)
return
obj[index] = value
output = decoder.decode('{}')
for line in lines:
path, obj = parse_line(line)
if path == ['']:
output = obj
continue
setitem(reduce(getitem, path[:-1], output), path[-1], obj)
return output
def to_str(obj):
ur"""
Coerce an object to a bytestring, utf-8-encoding if necessary.
>>> to_str("Hello World")
'Hello World'
>>> to_str(u"H\xe9llo")
'H\xc3\xa9llo'
"""
if isinstance(obj, unicode):
return obj.encode('utf-8')
elif hasattr(obj, '__unicode__'):
return unicode(obj).encode('utf-8')
return str(obj)
def is_value(obj):
"""
Determine whether an object is a simple JSON value.
The phrase 'simple JSON value' here means one of:
* String (Unicode or UTF-8-encoded bytestring)
* Number (integer or floating-point)
* Boolean
* `None`
"""
return isinstance(obj, (str, unicode, int, long, float, bool, type(None)))
import re
import calabash
import simplejson
import jsonpipe as jp
__all__ = ['jsonpipe', 'jsonunpipe', 'select', 'search_attr']
jsonpipe = calabash.pipe(jp.jsonpipe)
@calabash.pipe
def jsonunpipe(stdin, *args, **kwargs):
"""Calabash wrapper for :func:`jsonpipe.jsonunpipe`."""
yield jp.jsonunpipe(stdin, *args, **kwargs)
@calabash.pipe
def select(stdin, path, pathsep='/'):
r"""
Select only lines beginning with the given path.
This effectively selects a single JSON object and all its sub-objects.
>>> obj = {'a': 1, 'b': {'c': 3, 'd': 4}}
>>> list(jsonpipe(obj))
['/\t{}',
'/a\t1',
'/b\t{}',
'/b/c\t3',
'/b/d\t4']
>>> list(jsonpipe(obj) | select('/b'))
['/b\t{}',
'/b/c\t3',
'/b/d\t4']
>>> list(jsonpipe(obj) | select('/b') | jsonunpipe())
[{'b': {'c': 3, 'd': 4}}]
"""
path = re.sub(r'%s$' % re.escape(pathsep), r'', path)
return iter(stdin |
calabash.common.grep(r'^%s[\t%s]' % (
re.escape(path),
re.escape(pathsep))))
@calabash.pipe
def search_attr(stdin, attr, value, pathsep='/'):
r"""
Search stdin for an exact attr/value pair.
Yields paths to objects for which the given pair matches. Example:
>>> obj = {'a': 1, 'b': {'a': 2, 'c': {'a': "Hello"}}}
>>> list(jsonpipe(obj) | search_attr('a', 1))
['/']
>>> list(jsonpipe(obj) | search_attr('a', 2))
['/b']
>>> list(jsonpipe(obj) | search_attr('a', "Hello"))
['/b/c']
Multiple matches will result in multiple paths being yielded:
>>> obj = {'a': 1, 'b': {'a': 1, 'c': {'a': 1}}}
>>> list(jsonpipe(obj) | search_attr('a', 1))
['/', '/b', '/b/c']
"""
return iter(stdin |
# '...path/attribute\tvalue' => 'path'.
calabash.common.sed(r'^(.*)%s%s\t%s' % (
re.escape(pathsep),
re.escape(attr),
re.escape(simplejson.dumps(value))),
r'\1', exclusive=True) |
# Replace empty strings with the root pathsep.
calabash.common.sed(r'^$', pathsep))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment