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