You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

215 lines
6.7 KiB

4 years ago
  1. JMESPath
  2. ========
  3. .. image:: https://badges.gitter.im/Join Chat.svg
  4. :target: https://gitter.im/jmespath/chat
  5. .. image:: https://secure.travis-ci.org/jmespath/jmespath.py.png?branch=develop
  6. :target: http://travis-ci.org/jmespath/jmespath.py
  7. .. image:: https://codecov.io/github/jmespath/jmespath.py/coverage.svg?branch=develop
  8. :target: https://codecov.io/github/jmespath/jmespath.py?branch=develop
  9. JMESPath (pronounced "james path") allows you to declaratively specify how to
  10. extract elements from a JSON document.
  11. For example, given this document::
  12. {"foo": {"bar": "baz"}}
  13. The jmespath expression ``foo.bar`` will return "baz".
  14. JMESPath also supports:
  15. Referencing elements in a list. Given the data::
  16. {"foo": {"bar": ["one", "two"]}}
  17. The expression: ``foo.bar[0]`` will return "one".
  18. You can also reference all the items in a list using the ``*``
  19. syntax::
  20. {"foo": {"bar": [{"name": "one"}, {"name": "two"}]}}
  21. The expression: ``foo.bar[*].name`` will return ["one", "two"].
  22. Negative indexing is also supported (-1 refers to the last element
  23. in the list). Given the data above, the expression
  24. ``foo.bar[-1].name`` will return "two".
  25. The ``*`` can also be used for hash types::
  26. {"foo": {"bar": {"name": "one"}, "baz": {"name": "two"}}}
  27. The expression: ``foo.*.name`` will return ["one", "two"].
  28. API
  29. ===
  30. The ``jmespath.py`` library has two functions
  31. that operate on python data structures. You can use ``search``
  32. and give it the jmespath expression and the data:
  33. .. code:: python
  34. >>> import jmespath
  35. >>> path = jmespath.search('foo.bar', {'foo': {'bar': 'baz'}})
  36. 'baz'
  37. Similar to the ``re`` module, you can use the ``compile`` function
  38. to compile the JMESPath expression and use this parsed expression
  39. to perform repeated searches:
  40. .. code:: python
  41. >>> import jmespath
  42. >>> expression = jmespath.compile('foo.bar')
  43. >>> expression.search({'foo': {'bar': 'baz'}})
  44. 'baz'
  45. >>> expression.search({'foo': {'bar': 'other'}})
  46. 'other'
  47. This is useful if you're going to use the same jmespath expression to
  48. search multiple documents. This avoids having to reparse the
  49. JMESPath expression each time you search a new document.
  50. Options
  51. -------
  52. You can provide an instance of ``jmespath.Options`` to control how
  53. a JMESPath expression is evaluated. The most common scenario for
  54. using an ``Options`` instance is if you want to have ordered output
  55. of your dict keys. To do this you can use either of these options:
  56. .. code:: python
  57. >>> import jmespath
  58. >>> jmespath.search('{a: a, b: b},
  59. ... mydata,
  60. ... jmespath.Options(dict_cls=collections.OrderedDict))
  61. >>> import jmespath
  62. >>> parsed = jmespath.compile('{a: a, b: b}')
  63. >>> parsed.search('{a: a, b: b},
  64. ... 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.