jsonpath.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
  2. import logging
  3. import six
  4. from six.moves import xrange
  5. from itertools import *
  6. logger = logging.getLogger(__name__)
  7. # Turn on/off the automatic creation of id attributes
  8. # ... could be a kwarg pervasively but uses are rare and simple today
  9. auto_id_field = None
  10. class JSONPath(object):
  11. """
  12. The base class for JSONPath abstract syntax; those
  13. methods stubbed here are the interface to supported
  14. JSONPath semantics.
  15. """
  16. def find(self, data):
  17. """
  18. All `JSONPath` types support `find()`, which returns an iterable of `DatumInContext`s.
  19. They keep track of the path followed to the current location, so if the calling code
  20. has some opinion about that, it can be passed in here as a starting point.
  21. """
  22. raise NotImplementedError()
  23. def update(self, data, val):
  24. "Returns `data` with the specified path replaced by `val`"
  25. raise NotImplementedError()
  26. def child(self, child):
  27. """
  28. Equivalent to Child(self, next) but with some canonicalization
  29. """
  30. if isinstance(self, This) or isinstance(self, Root):
  31. return child
  32. elif isinstance(child, This):
  33. return self
  34. elif isinstance(child, Root):
  35. return child
  36. else:
  37. return Child(self, child)
  38. def make_datum(self, value):
  39. if isinstance(value, DatumInContext):
  40. return value
  41. else:
  42. return DatumInContext(value, path=Root(), context=None)
  43. class DatumInContext(object):
  44. """
  45. Represents a datum along a path from a context.
  46. Essentially a zipper but with a structure represented by JsonPath,
  47. and where the context is more of a parent pointer than a proper
  48. representation of the context.
  49. For quick-and-dirty work, this proxies any non-special attributes
  50. to the underlying datum, but the actual datum can (and usually should)
  51. be retrieved via the `value` attribute.
  52. To place `datum` within another, use `datum.in_context(context=..., path=...)`
  53. which extends the path. If the datum already has a context, it places the entire
  54. context within that passed in, so an object can be built from the inside
  55. out.
  56. """
  57. @classmethod
  58. def wrap(cls, data):
  59. if isinstance(data, cls):
  60. return data
  61. else:
  62. return cls(data)
  63. def __init__(self, value, path=None, context=None):
  64. self.value = value
  65. self.path = path or This()
  66. self.context = None if context is None else DatumInContext.wrap(context)
  67. def in_context(self, context, path):
  68. context = DatumInContext.wrap(context)
  69. if self.context:
  70. return DatumInContext(value=self.value, path=self.path, context=context.in_context(path=path, context=context))
  71. else:
  72. return DatumInContext(value=self.value, path=path, context=context)
  73. @property
  74. def full_path(self):
  75. return self.path if self.context is None else self.context.full_path.child(self.path)
  76. @property
  77. def id_pseudopath(self):
  78. """
  79. Looks like a path, but with ids stuck in when available
  80. """
  81. try:
  82. pseudopath = Fields(str(self.value[auto_id_field]))
  83. except (TypeError, AttributeError, KeyError): # This may not be all the interesting exceptions
  84. pseudopath = self.path
  85. if self.context:
  86. return self.context.id_pseudopath.child(pseudopath)
  87. else:
  88. return pseudopath
  89. def __repr__(self):
  90. return '%s(value=%r, path=%r, context=%r)' % (self.__class__.__name__, self.value, self.path, self.context)
  91. def __eq__(self, other):
  92. return isinstance(other, DatumInContext) and other.value == self.value and other.path == self.path and self.context == other.context
  93. class AutoIdForDatum(DatumInContext):
  94. """
  95. This behaves like a DatumInContext, but the value is
  96. always the path leading up to it, not including the "id",
  97. and with any "id" fields along the way replacing the prior
  98. segment of the path
  99. For example, it will make "foo.bar.id" return a datum
  100. that behaves like DatumInContext(value="foo.bar", path="foo.bar.id").
  101. This is disabled by default; it can be turned on by
  102. settings the `auto_id_field` global to a value other
  103. than `None`.
  104. """
  105. def __init__(self, datum, id_field=None):
  106. """
  107. Invariant is that datum.path is the path from context to datum. The auto id
  108. will either be the id in the datum (if present) or the id of the context
  109. followed by the path to the datum.
  110. The path to this datum is always the path to the context, the path to the
  111. datum, and then the auto id field.
  112. """
  113. self.datum = datum
  114. self.id_field = id_field or auto_id_field
  115. @property
  116. def value(self):
  117. return str(self.datum.id_pseudopath)
  118. @property
  119. def path(self):
  120. return self.id_field
  121. @property
  122. def context(self):
  123. return self.datum
  124. def __repr__(self):
  125. return '%s(%r)' % (self.__class__.__name__, self.datum)
  126. def in_context(self, context, path):
  127. return AutoIdForDatum(self.datum.in_context(context=context, path=path))
  128. def __eq__(self, other):
  129. return isinstance(other, AutoIdForDatum) and other.datum == self.datum and self.id_field == other.id_field
  130. class Root(JSONPath):
  131. """
  132. The JSONPath referring to the "root" object. Concrete syntax is '$'.
  133. The root is the topmost datum without any context attached.
  134. """
  135. def find(self, data):
  136. if not isinstance(data, DatumInContext):
  137. return [DatumInContext(data, path=Root(), context=None)]
  138. else:
  139. if data.context is None:
  140. return [DatumInContext(data.value, context=None, path=Root())]
  141. else:
  142. return Root().find(data.context)
  143. def update(self, data, val):
  144. return val
  145. def __str__(self):
  146. return '$'
  147. def __repr__(self):
  148. return 'Root()'
  149. def __eq__(self, other):
  150. return isinstance(other, Root)
  151. class This(JSONPath):
  152. """
  153. The JSONPath referring to the current datum. Concrete syntax is '@'.
  154. """
  155. def find(self, datum):
  156. return [DatumInContext.wrap(datum)]
  157. def update(self, data, val):
  158. return val
  159. def __str__(self):
  160. return '`this`'
  161. def __repr__(self):
  162. return 'This()'
  163. def __eq__(self, other):
  164. return isinstance(other, This)
  165. class Child(JSONPath):
  166. """
  167. JSONPath that first matches the left, then the right.
  168. Concrete syntax is <left> '.' <right>
  169. """
  170. def __init__(self, left, right):
  171. self.left = left
  172. self.right = right
  173. def find(self, datum):
  174. """
  175. Extra special case: auto ids do not have children,
  176. so cut it off right now rather than auto id the auto id
  177. """
  178. return [submatch
  179. for subdata in self.left.find(datum)
  180. if not isinstance(subdata, AutoIdForDatum)
  181. for submatch in self.right.find(subdata)]
  182. def __eq__(self, other):
  183. return isinstance(other, Child) and self.left == other.left and self.right == other.right
  184. def __str__(self):
  185. return '%s.%s' % (self.left, self.right)
  186. def __repr__(self):
  187. return '%s(%r, %r)' % (self.__class__.__name__, self.left, self.right)
  188. class Parent(JSONPath):
  189. """
  190. JSONPath that matches the parent node of the current match.
  191. Will crash if no such parent exists.
  192. Available via named operator `parent`.
  193. """
  194. def find(self, datum):
  195. datum = DatumInContext.wrap(datum)
  196. return [datum.context]
  197. def __eq__(self, other):
  198. return isinstance(other, Parent)
  199. def __str__(self):
  200. return '`parent`'
  201. def __repr__(self):
  202. return 'Parent()'
  203. class Where(JSONPath):
  204. """
  205. JSONPath that first matches the left, and then
  206. filters for only those nodes that have
  207. a match on the right.
  208. WARNING: Subject to change. May want to have "contains"
  209. or some other better word for it.
  210. """
  211. def __init__(self, left, right):
  212. self.left = left
  213. self.right = right
  214. def find(self, data):
  215. return [subdata for subdata in self.left.find(data) if self.right.find(subdata)]
  216. def __str__(self):
  217. return '%s where %s' % (self.left, self.right)
  218. def __eq__(self, other):
  219. return isinstance(other, Where) and other.left == self.left and other.right == self.right
  220. class Descendants(JSONPath):
  221. """
  222. JSONPath that matches first the left expression then any descendant
  223. of it which matches the right expression.
  224. """
  225. def __init__(self, left, right):
  226. self.left = left
  227. self.right = right
  228. def find(self, datum):
  229. # <left> .. <right> ==> <left> . (<right> | *..<right> | [*]..<right>)
  230. #
  231. # With with a wonky caveat that since Slice() has funky coercions
  232. # we cannot just delegate to that equivalence or we'll hit an
  233. # infinite loop. So right here we implement the coercion-free version.
  234. # Get all left matches into a list
  235. left_matches = self.left.find(datum)
  236. if not isinstance(left_matches, list):
  237. left_matches = [left_matches]
  238. def match_recursively(datum):
  239. right_matches = self.right.find(datum)
  240. # Manually do the * or [*] to avoid coercion and recurse just the right-hand pattern
  241. if isinstance(datum.value, list):
  242. recursive_matches = [submatch
  243. for i in range(0, len(datum.value))
  244. for submatch in match_recursively(DatumInContext(datum.value[i], context=datum, path=Index(i)))]
  245. elif isinstance(datum.value, dict):
  246. recursive_matches = [submatch
  247. for field in datum.value.keys()
  248. for submatch in match_recursively(DatumInContext(datum.value[field], context=datum, path=Fields(field)))]
  249. else:
  250. recursive_matches = []
  251. return right_matches + list(recursive_matches)
  252. # TODO: repeatable iterator instead of list?
  253. return [submatch
  254. for left_match in left_matches
  255. for submatch in match_recursively(left_match)]
  256. def is_singular():
  257. return False
  258. def __str__(self):
  259. return '%s..%s' % (self.left, self.right)
  260. def __eq__(self, other):
  261. return isinstance(other, Descendants) and self.left == other.left and self.right == other.right
  262. class Union(JSONPath):
  263. """
  264. JSONPath that returns the union of the results of each match.
  265. This is pretty shoddily implemented for now. The nicest semantics
  266. in case of mismatched bits (list vs atomic) is to put
  267. them all in a list, but I haven't done that yet.
  268. WARNING: Any appearance of this being the _concatenation_ is
  269. coincidence. It may even be a bug! (or laziness)
  270. """
  271. def __init__(self, left, right):
  272. self.left = left
  273. self.right = right
  274. def is_singular(self):
  275. return False
  276. def find(self, data):
  277. return self.left.find(data) + self.right.find(data)
  278. class Intersect(JSONPath):
  279. """
  280. JSONPath for bits that match *both* patterns.
  281. This can be accomplished a couple of ways. The most
  282. efficient is to actually build the intersected
  283. AST as in building a state machine for matching the
  284. intersection of regular languages. The next
  285. idea is to build a filtered data and match against
  286. that.
  287. """
  288. def __init__(self, left, right):
  289. self.left = left
  290. self.right = right
  291. def is_singular(self):
  292. return False
  293. def find(self, data):
  294. raise NotImplementedError()
  295. class Fields(JSONPath):
  296. """
  297. JSONPath referring to some field of the current object.
  298. Concrete syntax ix comma-separated field names.
  299. WARNING: If '*' is any of the field names, then they will
  300. all be returned.
  301. """
  302. def __init__(self, *fields):
  303. self.fields = fields
  304. def get_field_datum(self, datum, field):
  305. if field == auto_id_field:
  306. return AutoIdForDatum(datum)
  307. else:
  308. try:
  309. field_value = datum.value[field] # Do NOT use `val.get(field)` since that confuses None as a value and None due to `get`
  310. return DatumInContext(value=field_value, path=Fields(field), context=datum)
  311. except (TypeError, KeyError, AttributeError):
  312. return None
  313. def reified_fields(self, datum):
  314. if '*' not in self.fields:
  315. return self.fields
  316. else:
  317. try:
  318. fields = tuple(datum.value.keys())
  319. return fields if auto_id_field is None else fields + (auto_id_field,)
  320. except AttributeError:
  321. return ()
  322. def find(self, datum):
  323. datum = DatumInContext.wrap(datum)
  324. return [field_datum
  325. for field_datum in [self.get_field_datum(datum, field) for field in self.reified_fields(datum)]
  326. if field_datum is not None]
  327. def __str__(self):
  328. return ','.join(map(str, self.fields))
  329. def __repr__(self):
  330. return '%s(%s)' % (self.__class__.__name__, ','.join(map(repr, self.fields)))
  331. def __eq__(self, other):
  332. return isinstance(other, Fields) and tuple(self.fields) == tuple(other.fields)
  333. class Index(JSONPath):
  334. """
  335. JSONPath that matches indices of the current datum, or none if not large enough.
  336. Concrete syntax is brackets.
  337. WARNING: If the datum is not long enough, it will not crash but will not match anything.
  338. NOTE: For the concrete syntax of `[*]`, the abstract syntax is a Slice() with no parameters (equiv to `[:]`
  339. """
  340. def __init__(self, index):
  341. self.index = index
  342. def find(self, datum):
  343. datum = DatumInContext.wrap(datum)
  344. if len(datum.value) > self.index:
  345. return [DatumInContext(datum.value[self.index], path=self, context=datum)]
  346. else:
  347. return []
  348. def __eq__(self, other):
  349. return isinstance(other, Index) and self.index == other.index
  350. def __str__(self):
  351. return '[%i]' % self.index
  352. class Slice(JSONPath):
  353. """
  354. JSONPath matching a slice of an array.
  355. Because of a mismatch between JSON and XML when schema-unaware,
  356. this always returns an iterable; if the incoming data
  357. was not a list, then it returns a one element list _containing_ that
  358. data.
  359. Consider these two docs, and their schema-unaware translation to JSON:
  360. <a><b>hello</b></a> ==> {"a": {"b": "hello"}}
  361. <a><b>hello</b><b>goodbye</b></a> ==> {"a": {"b": ["hello", "goodbye"]}}
  362. If there were a schema, it would be known that "b" should always be an
  363. array (unless the schema were wonky, but that is too much to fix here)
  364. so when querying with JSON if the one writing the JSON knows that it
  365. should be an array, they can write a slice operator and it will coerce
  366. a non-array value to an array.
  367. This may be a bit unfortunate because it would be nice to always have
  368. an iterator, but dictionaries and other objects may also be iterable,
  369. so this is the compromise.
  370. """
  371. def __init__(self, start=None, end=None, step=None):
  372. self.start = start
  373. self.end = end
  374. self.step = step
  375. def find(self, datum):
  376. datum = DatumInContext.wrap(datum)
  377. # Here's the hack. If it is a dictionary or some kind of constant,
  378. # put it in a single-element list
  379. if (isinstance(datum.value, dict) or isinstance(datum.value, six.integer_types) or isinstance(datum.value, six.string_types)):
  380. return self.find(DatumInContext([datum.value], path=datum.path, context=datum.context))
  381. # Some iterators do not support slicing but we can still
  382. # at least work for '*'
  383. if self.start == None and self.end == None and self.step == None:
  384. return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in xrange(0, len(datum.value))]
  385. else:
  386. return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in range(0, len(datum.value))[self.start:self.end:self.step]]
  387. def __str__(self):
  388. if self.start == None and self.end == None and self.step == None:
  389. return '[*]'
  390. else:
  391. return '[%s%s%s]' % (self.start or '',
  392. ':%d'%self.end if self.end else '',
  393. ':%d'%self.step if self.step else '')
  394. def __repr__(self):
  395. return '%s(start=%r,end=%r,step=%r)' % (self.__class__.__name__, self.start, self.end, self.step)
  396. def __eq__(self, other):
  397. return isinstance(other, Slice) and other.start == self.start and self.end == other.end and other.step == self.step