README.rst 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. JMESPath
  2. ========
  3. .. image:: https://badges.gitter.im/Join Chat.svg
  4. :target: https://gitter.im/jmespath/chat
  5. JMESPath (pronounced "james path") allows you to declaratively specify how to
  6. extract elements from a JSON document.
  7. For example, given this document::
  8. {"foo": {"bar": "baz"}}
  9. The jmespath expression ``foo.bar`` will return "baz".
  10. JMESPath also supports:
  11. Referencing elements in a list. Given the data::
  12. {"foo": {"bar": ["one", "two"]}}
  13. The expression: ``foo.bar[0]`` will return "one".
  14. You can also reference all the items in a list using the ``*``
  15. syntax::
  16. {"foo": {"bar": [{"name": "one"}, {"name": "two"}]}}
  17. The expression: ``foo.bar[*].name`` will return ["one", "two"].
  18. Negative indexing is also supported (-1 refers to the last element
  19. in the list). Given the data above, the expression
  20. ``foo.bar[-1].name`` will return "two".
  21. The ``*`` can also be used for hash types::
  22. {"foo": {"bar": {"name": "one"}, "baz": {"name": "two"}}}
  23. The expression: ``foo.*.name`` will return ["one", "two"].
  24. Installation
  25. ============
  26. You can install JMESPath from pypi with:
  27. .. code:: bash
  28. pip install jmespath
  29. API
  30. ===
  31. The ``jmespath.py`` library has two functions
  32. that operate on python data structures. You can use ``search``
  33. and give it the jmespath expression and the data:
  34. .. code:: python
  35. >>> import jmespath
  36. >>> path = jmespath.search('foo.bar', {'foo': {'bar': 'baz'}})
  37. 'baz'
  38. Similar to the ``re`` module, you can use the ``compile`` function
  39. to compile the JMESPath expression and use this parsed expression
  40. to perform repeated searches:
  41. .. code:: python
  42. >>> import jmespath
  43. >>> expression = jmespath.compile('foo.bar')
  44. >>> expression.search({'foo': {'bar': 'baz'}})
  45. 'baz'
  46. >>> expression.search({'foo': {'bar': 'other'}})
  47. 'other'
  48. This is useful if you're going to use the same jmespath expression to
  49. search multiple documents. This avoids having to reparse the
  50. JMESPath expression each time you search a new document.
  51. Options
  52. -------
  53. You can provide an instance of ``jmespath.Options`` to control how
  54. a JMESPath expression is evaluated. The most common scenario for
  55. using an ``Options`` instance is if you want to have ordered output
  56. of your dict keys. To do this you can use either of these options:
  57. .. code:: python
  58. >>> import jmespath
  59. >>> jmespath.search('{a: a, b: b}',
  60. ... mydata,
  61. ... jmespath.Options(dict_cls=collections.OrderedDict))
  62. >>> import jmespath
  63. >>> parsed = jmespath.compile('{a: a, b: b}')
  64. >>> parsed.search(mydata,
  65. ... jmespath.Options(dict_cls=collections.OrderedDict))
  66. Custom Functions
  67. ~~~~~~~~~~~~~~~~
  68. The JMESPath language has numerous
  69. `built-in functions
  70. <http://jmespath.org/specification.html#built-in-functions>`__, but it is
  71. also possible to add your own custom functions. Keep in mind that
  72. custom function support in jmespath.py is experimental and the API may
  73. change based on feedback.
  74. **If you have a custom function that you've found useful, consider submitting
  75. it to jmespath.site and propose that it be added to the JMESPath language.**
  76. You can submit proposals
  77. `here <https://github.com/jmespath/jmespath.site/issues>`__.
  78. To create custom functions:
  79. * Create a subclass of ``jmespath.functions.Functions``.
  80. * Create a method with the name ``_func_<your function name>``.
  81. * Apply the ``jmespath.functions.signature`` decorator that indicates
  82. the expected types of the function arguments.
  83. * Provide an instance of your subclass in a ``jmespath.Options`` object.
  84. Below are a few examples:
  85. .. code:: python
  86. import jmespath
  87. from jmespath import functions
  88. # 1. Create a subclass of functions.Functions.
  89. # The function.Functions base class has logic
  90. # that introspects all of its methods and automatically
  91. # registers your custom functions in its function table.
  92. class CustomFunctions(functions.Functions):
  93. # 2 and 3. Create a function that starts with _func_
  94. # and decorate it with @signature which indicates its
  95. # expected types.
  96. # In this example, we're creating a jmespath function
  97. # called "unique_letters" that accepts a single argument
  98. # with an expected type "string".
  99. @functions.signature({'types': ['string']})
  100. def _func_unique_letters(self, s):
  101. # Given a string s, return a sorted
  102. # string of unique letters: 'ccbbadd' -> 'abcd'
  103. return ''.join(sorted(set(s)))
  104. # Here's another example. This is creating
  105. # a jmespath function called "my_add" that expects
  106. # two arguments, both of which should be of type number.
  107. @functions.signature({'types': ['number']}, {'types': ['number']})
  108. def _func_my_add(self, x, y):
  109. return x + y
  110. # 4. Provide an instance of your subclass in a Options object.
  111. options = jmespath.Options(custom_functions=CustomFunctions())
  112. # Provide this value to jmespath.search:
  113. # This will print 3
  114. print(
  115. jmespath.search(
  116. 'my_add(`1`, `2`)', {}, options=options)
  117. )
  118. # This will print "abcd"
  119. print(
  120. jmespath.search(
  121. 'foo.bar | unique_letters(@)',
  122. {'foo': {'bar': 'ccbbadd'}},
  123. options=options)
  124. )
  125. Again, if you come up with useful functions that you think make
  126. sense in the JMESPath language (and make sense to implement in all
  127. JMESPath libraries, not just python), please let us know at
  128. `jmespath.site <https://github.com/jmespath/jmespath.site/issues>`__.
  129. Specification
  130. =============
  131. If you'd like to learn more about the JMESPath language, you can check out
  132. the `JMESPath tutorial <http://jmespath.org/tutorial.html>`__. Also check
  133. out the `JMESPath examples page <http://jmespath.org/examples.html>`__ for
  134. examples of more complex jmespath queries.
  135. The grammar is specified using ABNF, as described in
  136. `RFC4234 <http://www.ietf.org/rfc/rfc4234.txt>`_.
  137. You can find the most up to date
  138. `grammar for JMESPath here <http://jmespath.org/specification.html#grammar>`__.
  139. You can read the full
  140. `JMESPath specification here <http://jmespath.org/specification.html>`__.
  141. Testing
  142. =======
  143. In addition to the unit tests for the jmespath modules,
  144. there is a ``tests/compliance`` directory that contains
  145. .json files with test cases. This allows other implementations
  146. to verify they are producing the correct output. Each json
  147. file is grouped by feature.
  148. Discuss
  149. =======
  150. Join us on our `Gitter channel <https://gitter.im/jmespath/chat>`__
  151. if you want to chat or if you have any questions.