json.vala 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /*
  2. * Copyright (c) 2012-2025 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. /*
  6. * Original C# code:
  7. * Public Domain Niklas Frykholm
  8. */
  9. namespace Crown
  10. {
  11. public errordomain JsonSyntaxError
  12. {
  13. BAD_TOKEN,
  14. BAD_VALUE,
  15. BAD_STRING,
  16. BAD_COMMENT
  17. }
  18. public errordomain JsonWriteError
  19. {
  20. BAD_VALUE
  21. }
  22. /// <summary>
  23. /// Provides functions for encoding and decoding files in the JSON format.
  24. /// </summary>
  25. [Compact]
  26. public class JSON
  27. {
  28. /// <summary>
  29. /// Encodes the hashtable t in the JSON format. The hash table can
  30. /// contain, numbers, bools, strings, ArrayLists and Hashtables.
  31. /// </summary>
  32. public static string encode(Value? t) throws JsonWriteError
  33. {
  34. StringBuilder sb = new StringBuilder();
  35. write(t, sb, 0);
  36. sb.append_c('\n');
  37. return sb.str;
  38. }
  39. /// <summary>
  40. /// Decodes a JSON bytestream into a hash table with numbers, bools, strings,
  41. /// ArrayLists and Hashtables.
  42. /// </summary>
  43. public static Value? decode(uint8[] sjson) throws JsonSyntaxError
  44. {
  45. int index = 0;
  46. return parse(sjson, ref index);
  47. }
  48. /// <summary>
  49. /// Convenience function for loading a file.
  50. /// </summary>
  51. public static Hashtable load(string path) throws JsonSyntaxError
  52. {
  53. FileStream fs = FileStream.open(path, "rb");
  54. if (fs == null)
  55. return new Hashtable();
  56. // Get file size
  57. fs.seek(0, FileSeek.END);
  58. size_t size = fs.tell();
  59. fs.rewind();
  60. if (size == 0)
  61. return new Hashtable();
  62. // Read whole file
  63. uint8[] bytes = new uint8[size];
  64. size_t bytes_read = fs.read(bytes);
  65. if (bytes_read != size)
  66. return new Hashtable();
  67. return decode(bytes) as Hashtable;
  68. }
  69. /// <summary>
  70. /// Convenience function for saving a file.
  71. /// </summary>
  72. public static void save(Hashtable h, string path) throws JsonWriteError
  73. {
  74. FileStream fs = FileStream.open(path, "wb");
  75. if (fs == null)
  76. return;
  77. fs.write(encode(h).data);
  78. }
  79. static void write_new_line(StringBuilder builder, int indentation)
  80. {
  81. if (builder.len > 0)
  82. builder.append_c('\n');
  83. for (int i = 0; i < indentation; ++i)
  84. builder.append_c('\t');
  85. }
  86. static void write(Value? o, StringBuilder builder, int indentation) throws JsonWriteError
  87. {
  88. if (o == null)
  89. builder.append("null");
  90. else if (o.holds(typeof(bool)) && (bool)o == false)
  91. builder.append("false");
  92. else if (o.holds(typeof(bool)))
  93. builder.append("true");
  94. else if (o.holds(typeof(int)))
  95. builder.append_printf("%d", (int)o);
  96. else if (o.holds(typeof(float)))
  97. builder.append_printf("%.9g", (float)o);
  98. else if (o.holds(typeof(double)))
  99. builder.append_printf("%.17g", (double)o);
  100. else if (o.holds(typeof(string)))
  101. write_string((string)o, builder);
  102. else if (o.holds(typeof(Gee.ArrayList)))
  103. write_array((Gee.ArrayList)o, builder, indentation);
  104. else if (o.holds(typeof(Hashtable)))
  105. write_object((Hashtable)o, builder, indentation);
  106. else
  107. throw new JsonWriteError.BAD_VALUE("Unsupported value type '%s'".printf(o.type_name()));
  108. }
  109. static void write_string(string s, StringBuilder builder)
  110. {
  111. builder.append_c('"');
  112. for (int i = 0; i < s.length; ++i) {
  113. uint8 c = s[i];
  114. if (c == '"' || c == '\\') {
  115. builder.append_c('\\');
  116. builder.append_c((char)c);
  117. } else if (c == '\n') {
  118. builder.append_c('\\');
  119. builder.append_c('n');
  120. } else {
  121. builder.append_c((char)c);
  122. }
  123. }
  124. builder.append_c('"');
  125. }
  126. static void write_array(Gee.ArrayList<Value?> a, StringBuilder builder, int indentation) throws JsonWriteError
  127. {
  128. bool write_comma = false;
  129. builder.append("[ ");
  130. foreach (Value? item in a) {
  131. if (write_comma)
  132. builder.append(", ");
  133. write(item, builder, indentation + 1);
  134. write_comma = true;
  135. }
  136. builder.append("]");
  137. }
  138. static void write_object(Hashtable t, StringBuilder builder, int indentation) throws JsonWriteError
  139. {
  140. builder.append_c('{');
  141. bool write_comma = false;
  142. foreach (var de in t.entries) {
  143. if (write_comma)
  144. builder.append(", ");
  145. write_new_line(builder, indentation);
  146. write(de.key, builder, indentation);
  147. builder.append(" : ");
  148. write(de.value, builder, indentation);
  149. write_comma = true;
  150. }
  151. write_new_line(builder, indentation);
  152. builder.append_c('}');
  153. }
  154. static void skip_whitespace(uint8[] json, ref int index)
  155. {
  156. while (index < json.length) {
  157. uint8 c = json[index];
  158. if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',')
  159. ++index;
  160. else
  161. break;
  162. }
  163. }
  164. static void consume(uint8[] json, ref int index, string consume) throws JsonSyntaxError
  165. {
  166. skip_whitespace(json, ref index);
  167. for (int i = 0; i < consume.length; ++i) {
  168. if (json[index] != consume[i])
  169. throw new JsonSyntaxError.BAD_TOKEN("Expected '%c' got '%c'".printf(consume[i], json[index]));
  170. ++index;
  171. }
  172. }
  173. static Value? parse(uint8[] json, ref int index) throws JsonSyntaxError
  174. {
  175. uint8 c = next(json, ref index);
  176. if (c == '{') {
  177. return parse_object(json, ref index);
  178. } else if (c == '[') {
  179. return parse_array(json, ref index);
  180. } else if (c == '"') {
  181. return parse_string(json, ref index);
  182. } else if (c == '-' || c >= '0' && c <= '9') {
  183. return parse_number(json, ref index);
  184. } else if (c == 't') {
  185. consume(json, ref index, "true");
  186. return true;
  187. } else if (c == 'f') {
  188. consume(json, ref index, "false");
  189. return false;
  190. } else if (c == 'n') {
  191. consume(json, ref index, "null");
  192. return null;
  193. } else {
  194. throw new JsonSyntaxError.BAD_VALUE("Bad value");
  195. }
  196. }
  197. static uint8 next(uint8[] json, ref int index)
  198. {
  199. skip_whitespace(json, ref index);
  200. return json[index];
  201. }
  202. static Hashtable parse_object(uint8[] json, ref int index) throws JsonSyntaxError
  203. {
  204. Hashtable ht = new Hashtable();
  205. consume(json, ref index, "{");
  206. skip_whitespace(json, ref index);
  207. while (next(json, ref index) != '}') {
  208. string key = parse_string(json, ref index);
  209. consume(json, ref index, ":");
  210. if (key.has_suffix("_binary"))
  211. ht[key] = (Value?)parse_binary(json, ref index);
  212. else
  213. ht[key] = parse(json, ref index);
  214. }
  215. consume(json, ref index, "}");
  216. return ht;
  217. }
  218. static Gee.ArrayList<Value?> parse_array(uint8[] json, ref int index) throws JsonSyntaxError
  219. {
  220. Gee.ArrayList<Value?> a = new Gee.ArrayList<Value?>();
  221. consume(json, ref index, "[");
  222. while (next(json, ref index) != ']') {
  223. Value? value = parse(json, ref index);
  224. a.add(value);
  225. }
  226. consume(json, ref index, "]");
  227. return a;
  228. }
  229. static uint8[] parse_binary(uint8[] json, ref int index) throws JsonSyntaxError
  230. {
  231. Gee.ArrayList<uint8> s = new Gee.ArrayList<uint8>();
  232. consume(json, ref index, "\"");
  233. while (true) {
  234. uint8 c = json[index];
  235. ++index;
  236. if (c == '"') {
  237. break;
  238. } else if (c != '\\') {
  239. s.add(c);
  240. } else {
  241. uint8 q = json[index];
  242. ++index;
  243. if (q == '"' || q == '\\' || q == '/')
  244. s.add(q);
  245. else if (q == 'b')
  246. s.add('\b');
  247. else if (q == 'f')
  248. s.add('\f');
  249. else if (q == 'n')
  250. s.add('\n');
  251. else if (q == 'r')
  252. s.add('\r');
  253. else if (q == 't')
  254. s.add('\t');
  255. else if (q == 'u')
  256. throw new JsonSyntaxError.BAD_STRING("Unsupported escape character 'u'");
  257. else
  258. throw new JsonSyntaxError.BAD_STRING("Bad string");
  259. }
  260. }
  261. s.add('\0');
  262. return s.to_array();
  263. }
  264. static string parse_string(uint8[] json, ref int index) throws JsonSyntaxError
  265. {
  266. return (string)parse_binary(json, ref index);
  267. }
  268. static double parse_number(uint8[] json, ref int index)
  269. {
  270. int end = index;
  271. while ("0123456789+-.eE".index_of_char((char)json[end]) != -1)
  272. ++end;
  273. uint8[] num = json[index : end];
  274. num += '\0';
  275. index = end;
  276. return double.parse((string)num);
  277. }
  278. }
  279. } /* namespace Crown */