JsonPath.cs 14 KB

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