PageRenderTime 74ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/src/cs/JsonPath.cs

http://jsonpath.googlecode.com/
C# | 498 lines | 366 code | 86 blank | 46 comment | 94 complexity | 231af495115867a1e59396f03a1f1ad1 MD5 | raw file
  1. //
  2. // C# implementation of JSONPath[1]
  3. //
  4. // Copyright (c) 2007 Atif Aziz (http://www.raboof.com/)
  5. // Licensed under The MIT License
  6. //
  7. // Supported targets:
  8. //
  9. // - Mono 1.1 or later
  10. // - Microsoft .NET Framework 1.0 or later
  11. //
  12. // [1] JSONPath - XPath for JSON
  13. // http://code.google.com/p/jsonpath/
  14. // Copyright (c) 2007 Stefan Goessner (goessner.net)
  15. // Licensed under The MIT License
  16. //
  17. #region The MIT License
  18. //
  19. // The MIT License
  20. //
  21. // Copyright (c) 2007 Atif Aziz (http://www.raboof.com/)
  22. //
  23. // Permission is hereby granted, free of charge, to any person obtaining a copy
  24. // of this software and associated documentation files (the "Software"), to deal
  25. // in the Software without restriction, including without limitation the rights
  26. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  27. // copies of the Software, and to permit persons to whom the Software is
  28. // furnished to do so, subject to the following conditions:
  29. //
  30. // The above copyright notice and this permission notice shall be included in
  31. // all copies or substantial portions of the Software.
  32. //
  33. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  34. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  35. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  36. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  39. // THE SOFTWARE.
  40. //
  41. #endregion
  42. namespace JsonPath
  43. {
  44. #region Imports
  45. using System;
  46. using System.Collections;
  47. using System.Diagnostics;
  48. using System.Globalization;
  49. using System.Text;
  50. using System.Text.RegularExpressions;
  51. #endregion
  52. public delegate object JsonPathScriptEvaluator(string script, object value, string context);
  53. public delegate void JsonPathResultAccumulator(object value, string[] indicies);
  54. public interface IJsonPathValueSystem
  55. {
  56. bool HasMember(object value, string member);
  57. object GetMemberValue(object value, string member);
  58. IEnumerable GetMembers(object value);
  59. bool IsObject(object value);
  60. bool IsArray(object value);
  61. bool IsPrimitive(object value);
  62. }
  63. [Serializable]
  64. public sealed class JsonPathNode
  65. {
  66. private readonly object value;
  67. private readonly string path;
  68. public JsonPathNode(object value, string path)
  69. {
  70. if (path == null)
  71. throw new ArgumentNullException("path");
  72. if (path.Length == 0)
  73. throw new ArgumentException("path");
  74. this.value = value;
  75. this.path = path;
  76. }
  77. public object Value
  78. {
  79. get { return value; }
  80. }
  81. public string Path
  82. {
  83. get { return path; }
  84. }
  85. public override string ToString()
  86. {
  87. return Path + " = " + Value;
  88. }
  89. public static object[] ValuesFrom(ICollection nodes)
  90. {
  91. object[] values = new object[nodes != null ? nodes.Count : 0];
  92. if (values.Length > 0)
  93. {
  94. Debug.Assert(nodes != null);
  95. int i = 0;
  96. foreach (JsonPathNode node in nodes)
  97. values[i++] = node.Value;
  98. }
  99. return values;
  100. }
  101. public static string[] PathsFrom(ICollection nodes)
  102. {
  103. string[] paths = new string[nodes != null ? nodes.Count : 0];
  104. if (paths.Length > 0)
  105. {
  106. Debug.Assert(nodes != null);
  107. int i = 0;
  108. foreach (JsonPathNode node in nodes)
  109. paths[i++] = node.Path;
  110. }
  111. return paths;
  112. }
  113. }
  114. public sealed class JsonPathContext
  115. {
  116. public static readonly JsonPathContext Default = new JsonPathContext();
  117. private JsonPathScriptEvaluator eval;
  118. private IJsonPathValueSystem system;
  119. public JsonPathScriptEvaluator ScriptEvaluator
  120. {
  121. get { return eval; }
  122. set { eval = value; }
  123. }
  124. public IJsonPathValueSystem ValueSystem
  125. {
  126. get { return system; }
  127. set { system = value; }
  128. }
  129. public void SelectTo(object obj, string expr, JsonPathResultAccumulator output)
  130. {
  131. if (obj == null)
  132. throw new ArgumentNullException("obj");
  133. if (output == null)
  134. throw new ArgumentNullException("output");
  135. Interpreter i = new Interpreter(output, ValueSystem, ScriptEvaluator);
  136. expr = Normalize(expr);
  137. if (expr.Length >= 1 && expr[0] == '$') // ^\$:?
  138. expr = expr.Substring(expr.Length >= 2 && expr[1] == ';' ? 2 : 1);
  139. i.Trace(expr, obj, "$");
  140. }
  141. public JsonPathNode[] SelectNodes(object obj, string expr)
  142. {
  143. ArrayList list = new ArrayList();
  144. SelectNodesTo(obj, expr, list);
  145. return (JsonPathNode[]) list.ToArray(typeof(JsonPathNode));
  146. }
  147. public IList SelectNodesTo(object obj, string expr, IList output)
  148. {
  149. ListAccumulator accumulator = new ListAccumulator(output != null ? output : new ArrayList());
  150. SelectTo(obj, expr, new JsonPathResultAccumulator(accumulator.Put));
  151. return output;
  152. }
  153. private static Regex RegExp(string pattern)
  154. {
  155. return new Regex(pattern, RegexOptions.ECMAScript);
  156. }
  157. private static string Normalize(string expr)
  158. {
  159. NormalizationSwap swap = new NormalizationSwap();
  160. expr = RegExp(@"[\['](\??\(.*?\))[\]']").Replace(expr, new MatchEvaluator(swap.Capture));
  161. expr = RegExp(@"'?\.'?|\['?").Replace(expr, ";");
  162. expr = RegExp(@";;;|;;").Replace(expr, ";..;");
  163. expr = RegExp(@";$|'?\]|'$").Replace(expr, string.Empty);
  164. expr = RegExp(@"#([0-9]+)").Replace(expr, new MatchEvaluator(swap.Yield));
  165. return expr;
  166. }
  167. private sealed class NormalizationSwap
  168. {
  169. private readonly ArrayList subx = new ArrayList(4);
  170. public string Capture(Match match)
  171. {
  172. Debug.Assert(match != null);
  173. int index = subx.Add(match.Groups[1].Value);
  174. return "[#" + index.ToString(CultureInfo.InvariantCulture) + "]";
  175. }
  176. public string Yield(Match match)
  177. {
  178. Debug.Assert(match != null);
  179. int index = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
  180. return (string) subx[index];
  181. }
  182. }
  183. public static string AsBracketNotation(string[] indicies)
  184. {
  185. if (indicies == null)
  186. throw new ArgumentNullException("indicies");
  187. StringBuilder sb = new StringBuilder();
  188. foreach (string index in indicies)
  189. {
  190. if (sb.Length == 0)
  191. {
  192. sb.Append('$');
  193. }
  194. else
  195. {
  196. sb.Append('[');
  197. if (RegExp(@"^[0-9*]+$").IsMatch(index))
  198. sb.Append(index);
  199. else
  200. sb.Append('\'').Append(index).Append('\'');
  201. sb.Append(']');
  202. }
  203. }
  204. return sb.ToString();
  205. }
  206. private static int ParseInt(string s)
  207. {
  208. return ParseInt(s, 0);
  209. }
  210. private static int ParseInt(string str, int defaultValue)
  211. {
  212. if (str == null || str.Length == 0)
  213. return defaultValue;
  214. try
  215. {
  216. return int.Parse(str, NumberStyles.None, CultureInfo.InvariantCulture);
  217. }
  218. catch (FormatException)
  219. {
  220. return defaultValue;
  221. }
  222. }
  223. private sealed class Interpreter
  224. {
  225. private readonly JsonPathResultAccumulator output;
  226. private readonly JsonPathScriptEvaluator eval;
  227. private readonly IJsonPathValueSystem system;
  228. private static readonly IJsonPathValueSystem defaultValueSystem = new BasicValueSystem();
  229. private static readonly char[] colon = new char[] { ':' };
  230. private static readonly char[] semicolon = new char[] { ';' };
  231. private delegate void WalkCallback(object member, string loc, string expr, object value, string path);
  232. public Interpreter(JsonPathResultAccumulator output, IJsonPathValueSystem valueSystem, JsonPathScriptEvaluator eval)
  233. {
  234. Debug.Assert(output != null);
  235. this.output = output;
  236. this.eval = eval != null ? eval : new JsonPathScriptEvaluator(NullEval);
  237. this.system = valueSystem != null ? valueSystem : defaultValueSystem;
  238. }
  239. public void Trace(string expr, object value, string path)
  240. {
  241. if (expr == null || expr.Length == 0)
  242. {
  243. Store(path, value);
  244. return;
  245. }
  246. int i = expr.IndexOf(';');
  247. string atom = i >= 0 ? expr.Substring(0, i) : expr;
  248. string tail = i >= 0 ? expr.Substring(i + 1) : string.Empty;
  249. if (value != null && system.HasMember(value, atom))
  250. {
  251. Trace(tail, Index(value, atom), path + ";" + atom);
  252. }
  253. else if (atom == "*")
  254. {
  255. Walk(atom, tail, value, path, new WalkCallback(WalkWild));
  256. }
  257. else if (atom == "..")
  258. {
  259. Trace(tail, value, path);
  260. Walk(atom, tail, value, path, new WalkCallback(WalkTree));
  261. }
  262. else if (atom.Length > 2 && atom[0] == '(' && atom[atom.Length - 1] == ')') // [(exp)]
  263. {
  264. Trace(eval(atom, value, path.Substring(path.LastIndexOf(';') + 1)) + ";" + tail, value, path);
  265. }
  266. else if (atom.Length > 3 && atom[0] == '?' && atom[1] == '(' && atom[atom.Length - 1] == ')') // [?(exp)]
  267. {
  268. Walk(atom, tail, value, path, new WalkCallback(WalkFiltered));
  269. }
  270. else if (RegExp(@"^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$").IsMatch(atom)) // [start:end:step] Phyton slice syntax
  271. {
  272. Slice(atom, tail, value, path);
  273. }
  274. else if (atom.IndexOf(',') >= 0) // [name1,name2,...]
  275. {
  276. foreach (string part in RegExp(@"'?,'?").Split(atom))
  277. Trace(part + ";" + tail, value, path);
  278. }
  279. }
  280. private void Store(string path, object value)
  281. {
  282. if (path != null)
  283. output(value, path.Split(semicolon));
  284. }
  285. private void Walk(string loc, string expr, object value, string path, WalkCallback callback)
  286. {
  287. if (system.IsPrimitive(value))
  288. return;
  289. if (system.IsArray(value))
  290. {
  291. IList list = (IList) value;
  292. for (int i = 0; i < list.Count; i++)
  293. callback(i, loc, expr, value, path);
  294. }
  295. else if (system.IsObject(value))
  296. {
  297. foreach (string key in system.GetMembers(value))
  298. callback(key, loc, expr, value, path);
  299. }
  300. }
  301. private void WalkWild(object member, string loc, string expr, object value, string path)
  302. {
  303. Trace(member + ";" + expr, value, path);
  304. }
  305. private void WalkTree(object member, string loc, string expr, object value, string path)
  306. {
  307. object result = Index(value, member.ToString());
  308. if (result != null && !system.IsPrimitive(result))
  309. Trace("..;" + expr, result, path + ";" + member);
  310. }
  311. private void WalkFiltered(object member, string loc, string expr, object value, string path)
  312. {
  313. object result = eval(RegExp(@"^\?\((.*?)\)$").Replace(loc, "$1"),
  314. Index(value, member.ToString()), member.ToString());
  315. if (Convert.ToBoolean(result, CultureInfo.InvariantCulture))
  316. Trace(member + ";" + expr, value, path);
  317. }
  318. private void Slice(string loc, string expr, object value, string path)
  319. {
  320. IList list = value as IList;
  321. if (list == null)
  322. return;
  323. int length = list.Count;
  324. string[] parts = loc.Split(colon);
  325. int start = ParseInt(parts[0]);
  326. int end = ParseInt(parts[1], list.Count);
  327. int step = parts.Length > 2 ? ParseInt(parts[2], 1) : 1;
  328. start = (start < 0) ? Math.Max(0, start + length) : Math.Min(length, start);
  329. end = (end < 0) ? Math.Max(0, end + length) : Math.Min(length, end);
  330. for (int i = start; i < end; i += step)
  331. Trace(i + ";" + expr, value, path);
  332. }
  333. private object Index(object obj, string member)
  334. {
  335. return system.GetMemberValue(obj, member);
  336. }
  337. private static object NullEval(string expr, object value, string context)
  338. {
  339. //
  340. // @ symbol in expr must be interpreted specially to resolve
  341. // to value. In JavaScript, the implementation would look
  342. // like:
  343. //
  344. // return obj && value && eval(expr.replace(/@/g, "value"));
  345. //
  346. return null;
  347. }
  348. }
  349. private sealed class BasicValueSystem : IJsonPathValueSystem
  350. {
  351. public bool HasMember(object value, string member)
  352. {
  353. if (IsPrimitive(value))
  354. return false;
  355. IDictionary dict = value as IDictionary;
  356. if (dict != null)
  357. return dict.Contains(member);
  358. IList list = value as IList;
  359. if (list != null)
  360. {
  361. int index = ParseInt(member, -1);
  362. return index >= 0 && index < list.Count;
  363. }
  364. return false;
  365. }
  366. public object GetMemberValue(object value, string member)
  367. {
  368. if (IsPrimitive(value))
  369. throw new ArgumentException("value");
  370. IDictionary dict = value as IDictionary;
  371. if (dict != null)
  372. return dict[member];
  373. IList list = (IList) value;
  374. int index = ParseInt(member, -1);
  375. if (index >= 0 && index < list.Count)
  376. return list[index];
  377. return null;
  378. }
  379. public IEnumerable GetMembers(object value)
  380. {
  381. return ((IDictionary) value).Keys;
  382. }
  383. public bool IsObject(object value)
  384. {
  385. return value is IDictionary;
  386. }
  387. public bool IsArray(object value)
  388. {
  389. return value is IList;
  390. }
  391. public bool IsPrimitive(object value)
  392. {
  393. if (value == null)
  394. throw new ArgumentNullException("value");
  395. return Type.GetTypeCode(value.GetType()) != TypeCode.Object;
  396. }
  397. }
  398. private sealed class ListAccumulator
  399. {
  400. private readonly IList list;
  401. public ListAccumulator(IList list)
  402. {
  403. Debug.Assert(list != null);
  404. this.list = list;
  405. }
  406. public void Put(object value, string[] indicies)
  407. {
  408. list.Add(new JsonPathNode(value, JsonPathContext.AsBracketNotation(indicies)));
  409. }
  410. }
  411. }
  412. }