JsonPathContext.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.Helper.Common.CollectionHelper;
  11. namespace WebTest.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. Console.WriteLine("mb:" + mb);
  210. if (value != null && mb)
  211. {
  212. Trace(tail, Index(value, atom), path + ";" + atom);
  213. }
  214. else if (atom.Equals("*"))
  215. {
  216. Walk(atom, tail, value, path, new WalkCallback(WalkWild));
  217. }
  218. else if (atom.Equals(".."))
  219. {
  220. Trace(tail, value, path);
  221. Walk(atom, tail, value, path, new WalkCallback(WalkTree));
  222. }
  223. else if (atom.Length > 2 && atom[0] == '(' && atom[atom.Length - 1] == ')') // [(exp)]
  224. {
  225. Trace(eval(atom, value, path.Substring(path.LastIndexOf(';') + 1)) + ";" + tail, value, path);
  226. }
  227. else if (atom.Length > 3 && atom[0] == '?' && atom[1] == '(' && atom[atom.Length - 1] == ')') // [?(exp)]
  228. {
  229. Walk(atom, tail, value, path, new WalkCallback(WalkFiltered));
  230. }
  231. else if (RegExp(@"^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$").IsMatch(atom)) // [start:end:step] Phyton slice syntax
  232. {
  233. Slice(atom, tail, value, path);
  234. }
  235. else if (atom.IndexOf(',') >= 0) // [name1,name2,...]
  236. {
  237. foreach (string part in RegExp(@"'?,'?").Split(atom))
  238. Trace(part + ";" + tail, value, path);
  239. }
  240. }
  241. private void Store(string path, object value)
  242. {
  243. if (path != null)
  244. output(value, path.Split(semicolon));
  245. }
  246. private void Walk(string loc, string expr, object value, string path, WalkCallback callback)
  247. {
  248. if (system.IsPrimitive(value)) {
  249. return;
  250. }
  251. if (system.IsArray(value))
  252. {
  253. if (value is JsonElement element)
  254. {
  255. IEnumerator enumerator = element.EnumerateArray().GetEnumerator();
  256. int i = 0;
  257. while (enumerator.MoveNext()) {
  258. callback(i, loc, expr, value, path);
  259. i += 1;
  260. }
  261. }
  262. else {
  263. IList list = (IList)value;
  264. for (int i = 0; i < list.Count; i++)
  265. callback(i, loc, expr, value, path);
  266. }
  267. }
  268. else if (system.IsObject(value))
  269. {
  270. IEnumerable mbs = system.GetMembers(value);
  271. foreach (string key in mbs)
  272. callback(key, loc, expr, value, path);
  273. }
  274. }
  275. private void WalkWild(object member, string loc, string expr, object value, string path)
  276. {
  277. Trace(member + ";" + expr, value, path);
  278. }
  279. private void WalkTree(object member, string loc, string expr, object value, string path)
  280. {
  281. object result = Index(value, member.ToString());
  282. if (result != null && !system.IsPrimitive(result))
  283. Trace("..;" + expr, result, path + ";" + member);
  284. }
  285. private void WalkFiltered(object member, string loc, string expr, object value, string path)
  286. {
  287. object result = eval(RegExp(@"^\?\((.*?)\)$").Replace(loc, "$1"),
  288. Index(value, member.ToString()), member.ToString());
  289. if (Convert.ToBoolean(result, CultureInfo.InvariantCulture))
  290. Trace(member + ";" + expr, value, path);
  291. }
  292. private void Slice(string loc, string expr, object value, string path)
  293. {
  294. IList list = value as IList;
  295. if (list == null)
  296. return;
  297. int length = list.Count;
  298. string[] parts = loc.Split(colon);
  299. int start = ParseInt(parts[0]);
  300. int end = ParseInt(parts[1], list.Count);
  301. int step = parts.Length > 2 ? ParseInt(parts[2], 1) : 1;
  302. start = (start < 0) ? Math.Max(0, start + length) : Math.Min(length, start);
  303. end = (end < 0) ? Math.Max(0, end + length) : Math.Min(length, end);
  304. for (int i = start; i < end; i += step)
  305. Trace(i + ";" + expr, value, path);
  306. }
  307. private object Index(object obj, string member)
  308. {
  309. object mbv = system.GetMemberValue(obj, member);
  310. return mbv;
  311. }
  312. private static object NullEval(string expr, object value, string context)
  313. {
  314. //
  315. // @ symbol in expr must be interpreted specially to resolve
  316. // to value. In JavaScript, the implementation would look
  317. // like:
  318. //
  319. // return obj && value && eval(expr.replace(/@/g, "value"));
  320. //
  321. return null;
  322. }
  323. }
  324. private sealed class BasicValueSystem : IJsonPathValueSystem
  325. {
  326. public bool HasMember(object value, string member)
  327. {
  328. if (IsPrimitive(value))
  329. return false;
  330. IDictionary dict = value as IDictionary;
  331. if (dict != null)
  332. return dict.Contains(member);
  333. IList list = value as IList;
  334. if (list != null)
  335. {
  336. int index = ParseInt(member, -1);
  337. return index >= 0 && index < list.Count;
  338. }
  339. object obj = value as object;
  340. if (obj != null)
  341. {
  342. IDictionary<string,object> dis = obj.ToDictionary();
  343. return dis.ContainsKey(member);
  344. }
  345. return false;
  346. }
  347. public object GetMemberValue(object value, string member)
  348. {
  349. if (IsPrimitive(value))
  350. throw new ArgumentException("value");
  351. IDictionary dict = value as IDictionary;
  352. if (dict != null)
  353. return dict[member];
  354. IList list = (IList)value;
  355. int index = ParseInt(member, -1);
  356. if (index >= 0 && index < list.Count)
  357. return list[index];
  358. return null;
  359. }
  360. public IEnumerable GetMembers(object value)
  361. {
  362. return ((IDictionary)value).Keys;
  363. }
  364. public bool IsObject(object value)
  365. {
  366. return value is IDictionary;
  367. }
  368. public bool IsArray(object value)
  369. {
  370. return value is IList;
  371. }
  372. public bool IsPrimitive(object value)
  373. {
  374. if (value == null)
  375. throw new ArgumentNullException("value");
  376. return Type.GetTypeCode(value.GetType()) != TypeCode.Object;
  377. }
  378. }
  379. private sealed class ListAccumulator
  380. {
  381. private readonly IList list;
  382. public ListAccumulator(IList list)
  383. {
  384. Debug.Assert(list != null);
  385. this.list = list;
  386. }
  387. public void Put(object value, string[] indicies)
  388. {
  389. list.Add(new JsonPathNode(value, JsonPathContext.AsBracketNotation(indicies)));
  390. }
  391. }
  392. }
  393. }