JsonPathContext.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Text.RegularExpressions;
  10. using TEAMModelOS.SDK;
  11. namespace TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath
  12. {
  13. /// <summary>
  14. /// 语法文档 https://www.cnblogs.com/aoyihuashao/p/8665873.html
  15. /// </summary>
  16. /// <param name="script"></param>
  17. /// <param name="value"></param>
  18. /// <param name="context"></param>
  19. /// <returns></returns>
  20. public delegate object JsonPathScriptEvaluator(string script, object value, string context);
  21. public delegate void JsonPathResultAccumulator(object value, string[] indicies);
  22. [Serializable]
  23. public sealed class JsonPathNode
  24. {
  25. private readonly object value;
  26. private readonly string path;
  27. public JsonPathNode(object value, string path)
  28. {
  29. if (path == null)
  30. throw new ArgumentNullException("path");
  31. if (path.Length == 0)
  32. throw new ArgumentException("path");
  33. this.value = value;
  34. this.path = path;
  35. }
  36. public object Value
  37. {
  38. get { return value; }
  39. }
  40. public string Path
  41. {
  42. get { return path; }
  43. }
  44. public override string ToString()
  45. {
  46. return Path + " = " + Value;
  47. }
  48. public static object[] ValuesFrom(ICollection nodes)
  49. {
  50. object[] values = new object[nodes != null ? nodes.Count : 0];
  51. if (values.Length > 0)
  52. {
  53. Debug.Assert(nodes != null);
  54. int i = 0;
  55. foreach (JsonPathNode node in nodes)
  56. values[i++] = node.Value;
  57. }
  58. return values;
  59. }
  60. public static string[] PathsFrom(ICollection nodes)
  61. {
  62. string[] paths = new string[nodes != null ? nodes.Count : 0];
  63. if (paths.Length > 0)
  64. {
  65. Debug.Assert(nodes != null);
  66. int i = 0;
  67. foreach (JsonPathNode node in nodes)
  68. paths[i++] = node.Path;
  69. }
  70. return paths;
  71. }
  72. }
  73. public sealed class JsonPathContext
  74. {
  75. public static readonly JsonPathContext Default = new JsonPathContext();
  76. private JsonPathScriptEvaluator eval;
  77. private IJsonPathValueSystem system;
  78. public JsonPathScriptEvaluator ScriptEvaluator
  79. {
  80. get { return eval; }
  81. set { eval = value; }
  82. }
  83. public IJsonPathValueSystem ValueSystem
  84. {
  85. get { return system; }
  86. set { system = value; }
  87. }
  88. public void SelectTo(object obj, string expr, JsonPathResultAccumulator output)
  89. {
  90. if (obj == null)
  91. throw new ArgumentNullException("obj");
  92. if (output == null)
  93. throw new ArgumentNullException("output");
  94. Interpreter i = new Interpreter(output, ValueSystem, ScriptEvaluator);
  95. expr = Normalize(expr);
  96. if (expr.Length >= 1 && expr[0] == '$') // ^\$:?
  97. expr = expr.Substring(expr.Length >= 2 && expr[1] == ';' ? 2 : 1);
  98. i.Trace(expr, obj, "$");
  99. }
  100. public JsonPathNode[] SelectNodes(object obj, string expr)
  101. {
  102. ArrayList list = new ArrayList();
  103. SelectNodesTo(obj, expr, list);
  104. return (JsonPathNode[])list.ToArray(typeof(JsonPathNode));
  105. }
  106. public IList SelectNodesTo(object obj, string expr, IList output)
  107. {
  108. ListAccumulator accumulator = new ListAccumulator(output != null ? output : new ArrayList());
  109. SelectTo(obj, expr, new JsonPathResultAccumulator(accumulator.Put));
  110. return output;
  111. }
  112. private static Regex RegExp(string pattern)
  113. {
  114. return new Regex(pattern, RegexOptions.ECMAScript);
  115. }
  116. private static string Normalize(string expr)
  117. {
  118. NormalizationSwap swap = new NormalizationSwap();
  119. expr = RegExp(@"[\['](\??\(.*?\))[\]']").Replace(expr, new MatchEvaluator(swap.Capture));
  120. expr = RegExp(@"'?\.'?|\['?").Replace(expr, ";");
  121. expr = RegExp(@";;;|;;").Replace(expr, ";..;");
  122. expr = RegExp(@";$|'?\]|'$").Replace(expr, string.Empty);
  123. expr = RegExp(@"#([0-9]+)").Replace(expr, new MatchEvaluator(swap.Yield));
  124. return expr;
  125. }
  126. private sealed class NormalizationSwap
  127. {
  128. private readonly ArrayList subx = new ArrayList(4);
  129. public string Capture(Match match)
  130. {
  131. Debug.Assert(match != null);
  132. int index = subx.Add(match.Groups[1].Value);
  133. return "[#" + index.ToString(CultureInfo.InvariantCulture) + "]";
  134. }
  135. public string Yield(Match match)
  136. {
  137. Debug.Assert(match != null);
  138. int index = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
  139. return (string)subx[index];
  140. }
  141. }
  142. public static string AsBracketNotation(string[] indicies)
  143. {
  144. if (indicies == null)
  145. throw new ArgumentNullException("indicies");
  146. StringBuilder sb = new StringBuilder();
  147. foreach (string index in indicies)
  148. {
  149. if (sb.Length == 0)
  150. {
  151. sb.Append('$');
  152. }
  153. else
  154. {
  155. sb.Append('[');
  156. if (RegExp(@"^[0-9*]+$").IsMatch(index))
  157. sb.Append(index);
  158. else
  159. sb.Append('\'').Append(index).Append('\'');
  160. sb.Append(']');
  161. }
  162. }
  163. return sb.ToString();
  164. }
  165. private static int ParseInt(string s)
  166. {
  167. return ParseInt(s, 0);
  168. }
  169. private static int ParseInt(string str, int defaultValue)
  170. {
  171. if (str == null || str.Length == 0)
  172. return defaultValue;
  173. try
  174. {
  175. return int.Parse(str, NumberStyles.None, CultureInfo.InvariantCulture);
  176. }
  177. catch (FormatException)
  178. {
  179. return defaultValue;
  180. }
  181. }
  182. private sealed class Interpreter
  183. {
  184. private readonly JsonPathResultAccumulator output;
  185. private readonly JsonPathScriptEvaluator eval;
  186. private readonly IJsonPathValueSystem system;
  187. private static readonly IJsonPathValueSystem defaultValueSystem = new BasicValueSystem();
  188. private static readonly char[] colon = new char[] { ':' };
  189. private static readonly char[] semicolon = new char[] { ';' };
  190. private delegate void WalkCallback(object member, string loc, string expr, object value, string path);
  191. public Interpreter(JsonPathResultAccumulator output, IJsonPathValueSystem valueSystem, JsonPathScriptEvaluator eval)
  192. {
  193. Debug.Assert(output != null);
  194. this.output = output;
  195. this.eval = eval != null ? eval : new JsonPathScriptEvaluator(NullEval);
  196. this.system = valueSystem != null ? valueSystem : defaultValueSystem;
  197. }
  198. public void Trace(string expr, object value, string path)
  199. {
  200. if (expr == null || expr.Length == 0)
  201. {
  202. Store(path, value);
  203. return;
  204. }
  205. int i = expr.IndexOf(';');
  206. string atom = i >= 0 ? expr.Substring(0, i) : expr;
  207. string tail = i >= 0 ? expr.Substring(i + 1) : string.Empty;
  208. bool mb = system.HasMember(value, atom);
  209. if (value != null && mb)
  210. {
  211. Trace(tail, Index(value, atom), path + ";" + atom);
  212. }
  213. else if (atom.Equals("*"))
  214. {
  215. Walk(atom, tail, value, path, new WalkCallback(WalkWild));
  216. }
  217. else if (atom.Equals(".."))
  218. {
  219. Trace(tail, value, path);
  220. Walk(atom, tail, value, path, new WalkCallback(WalkTree));
  221. }
  222. else if (atom.Length > 2 && atom[0] == '(' && atom[atom.Length - 1] == ')') // [(exp)]
  223. {
  224. Trace(eval(atom, value, path.Substring(path.LastIndexOf(';') + 1)) + ";" + tail, value, path);
  225. }
  226. else if (atom.Length > 3 && atom[0] == '?' && atom[1] == '(' && atom[atom.Length - 1] == ')') // [?(exp)]
  227. {
  228. Walk(atom, tail, value, path, new WalkCallback(WalkFiltered));
  229. }
  230. else if (RegExp(@"^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$").IsMatch(atom)) // [start:end:step] Phyton slice syntax
  231. {
  232. Slice(atom, tail, value, path);
  233. }
  234. else if (atom.IndexOf(',') >= 0) // [name1,name2,...]
  235. {
  236. foreach (string part in RegExp(@"'?,'?").Split(atom))
  237. Trace(part + ";" + tail, value, path);
  238. }
  239. }
  240. private void Store(string path, object value)
  241. {
  242. if (path != null)
  243. output(value, path.Split(semicolon));
  244. }
  245. private void Walk(string loc, string expr, object value, string path, WalkCallback callback)
  246. {
  247. if (system.IsPrimitive(value)) {
  248. return;
  249. }
  250. if (system.IsArray(value))
  251. {
  252. if (value is JsonElement element)
  253. {
  254. IEnumerator enumerator = element.EnumerateArray().GetEnumerator();
  255. int i = 0;
  256. while (enumerator.MoveNext()) {
  257. callback(i, loc, expr, value, path);
  258. i += 1;
  259. }
  260. }
  261. else {
  262. IList list = (IList)value;
  263. for (int i = 0; i < list.Count; i++)
  264. callback(i, loc, expr, value, path);
  265. }
  266. }
  267. else if (system.IsObject(value))
  268. {
  269. IEnumerable mbs = system.GetMembers(value);
  270. foreach (string key in mbs)
  271. callback(key, loc, expr, value, path);
  272. }
  273. }
  274. private void WalkWild(object member, string loc, string expr, object value, string path)
  275. {
  276. Trace(member + ";" + expr, value, path);
  277. }
  278. private void WalkTree(object member, string loc, string expr, object value, string path)
  279. {
  280. object result = Index(value, member.ToString());
  281. if (result != null && !system.IsPrimitive(result))
  282. Trace("..;" + expr, result, path + ";" + member);
  283. }
  284. private void WalkFiltered(object member, string loc, string expr, object value, string path)
  285. {
  286. object result = eval(RegExp(@"^\?\((.*?)\)$").Replace(loc, "$1"),
  287. Index(value, member.ToString()), member.ToString());
  288. if (Convert.ToBoolean(result, CultureInfo.InvariantCulture))
  289. Trace(member + ";" + expr, value, path);
  290. }
  291. private void Slice(string loc, string expr, object value, string path)
  292. {
  293. IList list = value as IList;
  294. if (list == null)
  295. return;
  296. int length = list.Count;
  297. string[] parts = loc.Split(colon);
  298. int start = ParseInt(parts[0]);
  299. int end = ParseInt(parts[1], list.Count);
  300. int step = parts.Length > 2 ? ParseInt(parts[2], 1) : 1;
  301. start = (start < 0) ? Math.Max(0, start + length) : Math.Min(length, start);
  302. end = (end < 0) ? Math.Max(0, end + length) : Math.Min(length, end);
  303. for (int i = start; i < end; i += step)
  304. Trace(i + ";" + expr, value, path);
  305. }
  306. private object Index(object obj, string member)
  307. {
  308. object mbv = system.GetMemberValue(obj, member);
  309. return mbv;
  310. }
  311. private static object NullEval(string expr, object value, string context)
  312. {
  313. //
  314. // @ symbol in expr must be interpreted specially to resolve
  315. // to value. In JavaScript, the implementation would look
  316. // like:
  317. //
  318. // return obj && value && eval(expr.replace(/@/g, "value"));
  319. //
  320. return null;
  321. }
  322. }
  323. private sealed class BasicValueSystem : IJsonPathValueSystem
  324. {
  325. public bool HasMember(object value, string member)
  326. {
  327. if (IsPrimitive(value))
  328. return false;
  329. IDictionary dict = value as IDictionary;
  330. if (dict != null)
  331. return dict.Contains(member);
  332. IList list = value as IList;
  333. if (list != null)
  334. {
  335. int index = ParseInt(member, -1);
  336. return index >= 0 && index < list.Count;
  337. }
  338. object obj = value as object;
  339. if (obj != null)
  340. {
  341. IDictionary<string,object> dis = obj.ToDictionary();
  342. return dis.ContainsKey(member);
  343. }
  344. return false;
  345. }
  346. public object GetMemberValue(object value, string member)
  347. {
  348. if (IsPrimitive(value))
  349. throw new ArgumentException("value");
  350. IDictionary dict = value as IDictionary;
  351. if (dict != null)
  352. return dict[member];
  353. IList list = (IList)value;
  354. int index = ParseInt(member, -1);
  355. if (index >= 0 && index < list.Count)
  356. return list[index];
  357. return null;
  358. }
  359. public IEnumerable GetMembers(object value)
  360. {
  361. return ((IDictionary)value).Keys;
  362. }
  363. public bool IsObject(object value)
  364. {
  365. return value is IDictionary;
  366. }
  367. public bool IsArray(object value)
  368. {
  369. return value is IList;
  370. }
  371. public bool IsPrimitive(object value)
  372. {
  373. if (value == null)
  374. throw new ArgumentNullException("value");
  375. return Type.GetTypeCode(value.GetType()) != TypeCode.Object;
  376. }
  377. }
  378. private sealed class ListAccumulator
  379. {
  380. private readonly IList list;
  381. public ListAccumulator(IList list)
  382. {
  383. Debug.Assert(list != null);
  384. this.list = list;
  385. }
  386. public void Put(object value, string[] indicies)
  387. {
  388. list.Add(new JsonPathNode(value, JsonPathContext.AsBracketNotation(indicies)));
  389. }
  390. }
  391. }
  392. }