22Author : zhangxianbing
33Date : 2020-12-27 09:22:14
44LastEditors : zhangxianbing
5- LastEditTime : 2021-03-02 15:56:00
5+ LastEditTime : 2021-03-02 19:08:30
66Description : JSONPath
77"""
88__version__ = "1.0.4"
1212import logging
1313import os
1414import re
15+ import sys
1516from collections import defaultdict
1617from typing import Union
1718
@@ -57,6 +58,8 @@ class JSONPath:
5758 # save special patterns
5859 REP_GET_QUOTE = re .compile (r"['](.*?)[']" )
5960 REP_PUT_QUOTE = re .compile (r"#Q(\d+)" )
61+ REP_GET_BACKQUOTE = re .compile (r"[`](.*?)[`]" )
62+ REP_PUT_BACKQUOTE = re .compile (r"#BQ(\d+)" )
6063 REP_GET_BRACKET = re .compile (r"[\[](.*?)[\]]" )
6164 REP_PUT_BRACKET = re .compile (r"#B(\d+)" )
6265 REP_GET_PAREN = re .compile (r"[\(](.*?)[\)]" )
@@ -82,6 +85,8 @@ def __init__(self, expr: str):
8285 self .lpath = len (self .segments )
8386 logger .debug (f"segments : { self .segments } " )
8487
88+ self .caller_globals = sys ._getframe (1 ).f_globals
89+
8590 def parse (self , obj , result_type = "VALUE" ):
8691 if not isinstance (obj , (list , dict )):
8792 raise TypeError ("obj must be a list or a dict." )
@@ -99,21 +104,26 @@ def parse(self, obj, result_type="VALUE"):
99104
100105 def _parse_expr (self , expr ):
101106 logger .debug (f"before expr : { expr } " )
102-
107+ # pick up special patterns
103108 expr = JSONPath .REP_GET_QUOTE .sub (self ._get_quote , expr )
109+ expr = JSONPath .REP_GET_BACKQUOTE .sub (self ._get_backquote , expr )
104110 expr = JSONPath .REP_GET_BRACKET .sub (self ._get_bracket , expr )
105111 expr = JSONPath .REP_GET_PAREN .sub (self ._get_paren , expr )
112+ # split
106113 expr = JSONPath .REP_DOUBLEDOT .sub (f"{ JSONPath .SEP } ..{ JSONPath .SEP } " , expr )
107114 expr = JSONPath .REP_DOT .sub (JSONPath .SEP , expr )
115+ # put back
108116 expr = JSONPath .REP_PUT_PAREN .sub (self ._put_paren , expr )
109117 expr = JSONPath .REP_PUT_BRACKET .sub (self ._put_bracket , expr )
118+ expr = JSONPath .REP_PUT_BACKQUOTE .sub (self ._put_backquote , expr )
110119 expr = JSONPath .REP_PUT_QUOTE .sub (self ._put_quote , expr )
111120 if expr .startswith ("$;" ):
112121 expr = expr [2 :]
113122
114123 logger .debug (f"after expr : { expr } " )
115124 return expr
116125
126+ # TODO abstract get and put procedures
117127 def _get_quote (self , m ):
118128 n = len (self .subx ["#Q" ])
119129 self .subx ["#Q" ].append (m .group (1 ))
@@ -122,6 +132,14 @@ def _get_quote(self, m):
122132 def _put_quote (self , m ):
123133 return self .subx ["#Q" ][int (m .group (1 ))]
124134
135+ def _get_backquote (self , m ):
136+ n = len (self .subx ["#BQ" ])
137+ self .subx ["#BQ" ].append (m .group (1 ))
138+ return f"`#BQ{ n } `"
139+
140+ def _put_backquote (self , m ):
141+ return self .subx ["#BQ" ][int (m .group (1 ))]
142+
125143 def _get_bracket (self , m ):
126144 n = len (self .subx ["#B" ])
127145 self .subx ["#B" ].append (m .group (1 ))
0 commit comments