json.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*************************************************************************/
  2. /* json.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "json.h"
  31. #include "core/string/print_string.h"
  32. const char *JSON::tk_name[TK_MAX] = {
  33. "'{'",
  34. "'}'",
  35. "'['",
  36. "']'",
  37. "identifier",
  38. "string",
  39. "number",
  40. "':'",
  41. "','",
  42. "EOF",
  43. };
  44. String JSON::_make_indent(const String &p_indent, int p_size) {
  45. String indent_text = "";
  46. if (!p_indent.is_empty()) {
  47. for (int i = 0; i < p_size; i++) {
  48. indent_text += p_indent;
  49. }
  50. }
  51. return indent_text;
  52. }
  53. String JSON::_stringify(const Variant &p_var, const String &p_indent, int p_cur_indent, bool p_sort_keys, HashSet<const void *> &p_markers, bool p_full_precision) {
  54. ERR_FAIL_COND_V_MSG(p_cur_indent > Variant::MAX_RECURSION_DEPTH, "...", "JSON structure is too deep. Bailing.");
  55. String colon = ":";
  56. String end_statement = "";
  57. if (!p_indent.is_empty()) {
  58. colon += " ";
  59. end_statement += "\n";
  60. }
  61. switch (p_var.get_type()) {
  62. case Variant::NIL:
  63. return "null";
  64. case Variant::BOOL:
  65. return p_var.operator bool() ? "true" : "false";
  66. case Variant::INT:
  67. return itos(p_var);
  68. case Variant::FLOAT: {
  69. double num = p_var;
  70. if (p_full_precision) {
  71. // Store unreliable digits (17) instead of just reliable
  72. // digits (14) so that the value can be decoded exactly.
  73. return String::num(num, 17 - (int)floor(log10(num)));
  74. } else {
  75. // Store only reliable digits (14) by default.
  76. return String::num(num, 14 - (int)floor(log10(num)));
  77. }
  78. }
  79. case Variant::PACKED_INT32_ARRAY:
  80. case Variant::PACKED_INT64_ARRAY:
  81. case Variant::PACKED_FLOAT32_ARRAY:
  82. case Variant::PACKED_FLOAT64_ARRAY:
  83. case Variant::PACKED_STRING_ARRAY:
  84. case Variant::ARRAY: {
  85. String s = "[";
  86. s += end_statement;
  87. Array a = p_var;
  88. ERR_FAIL_COND_V_MSG(p_markers.has(a.id()), "\"[...]\"", "Converting circular structure to JSON.");
  89. p_markers.insert(a.id());
  90. for (int i = 0; i < a.size(); i++) {
  91. if (i > 0) {
  92. s += ",";
  93. s += end_statement;
  94. }
  95. s += _make_indent(p_indent, p_cur_indent + 1) + _stringify(a[i], p_indent, p_cur_indent + 1, p_sort_keys, p_markers);
  96. }
  97. s += end_statement + _make_indent(p_indent, p_cur_indent) + "]";
  98. p_markers.erase(a.id());
  99. return s;
  100. }
  101. case Variant::DICTIONARY: {
  102. String s = "{";
  103. s += end_statement;
  104. Dictionary d = p_var;
  105. ERR_FAIL_COND_V_MSG(p_markers.has(d.id()), "\"{...}\"", "Converting circular structure to JSON.");
  106. p_markers.insert(d.id());
  107. List<Variant> keys;
  108. d.get_key_list(&keys);
  109. if (p_sort_keys) {
  110. keys.sort();
  111. }
  112. bool first_key = true;
  113. for (const Variant &E : keys) {
  114. if (first_key) {
  115. first_key = false;
  116. } else {
  117. s += ",";
  118. s += end_statement;
  119. }
  120. s += _make_indent(p_indent, p_cur_indent + 1) + _stringify(String(E), p_indent, p_cur_indent + 1, p_sort_keys, p_markers);
  121. s += colon;
  122. s += _stringify(d[E], p_indent, p_cur_indent + 1, p_sort_keys, p_markers);
  123. }
  124. s += end_statement + _make_indent(p_indent, p_cur_indent) + "}";
  125. p_markers.erase(d.id());
  126. return s;
  127. }
  128. default:
  129. return "\"" + String(p_var).json_escape() + "\"";
  130. }
  131. }
  132. Error JSON::_get_token(const char32_t *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str) {
  133. while (p_len > 0) {
  134. switch (p_str[index]) {
  135. case '\n': {
  136. line++;
  137. index++;
  138. break;
  139. }
  140. case 0: {
  141. r_token.type = TK_EOF;
  142. return OK;
  143. } break;
  144. case '{': {
  145. r_token.type = TK_CURLY_BRACKET_OPEN;
  146. index++;
  147. return OK;
  148. }
  149. case '}': {
  150. r_token.type = TK_CURLY_BRACKET_CLOSE;
  151. index++;
  152. return OK;
  153. }
  154. case '[': {
  155. r_token.type = TK_BRACKET_OPEN;
  156. index++;
  157. return OK;
  158. }
  159. case ']': {
  160. r_token.type = TK_BRACKET_CLOSE;
  161. index++;
  162. return OK;
  163. }
  164. case ':': {
  165. r_token.type = TK_COLON;
  166. index++;
  167. return OK;
  168. }
  169. case ',': {
  170. r_token.type = TK_COMMA;
  171. index++;
  172. return OK;
  173. }
  174. case '"': {
  175. index++;
  176. String str;
  177. while (true) {
  178. if (p_str[index] == 0) {
  179. r_err_str = "Unterminated String";
  180. return ERR_PARSE_ERROR;
  181. } else if (p_str[index] == '"') {
  182. index++;
  183. break;
  184. } else if (p_str[index] == '\\') {
  185. //escaped characters...
  186. index++;
  187. char32_t next = p_str[index];
  188. if (next == 0) {
  189. r_err_str = "Unterminated String";
  190. return ERR_PARSE_ERROR;
  191. }
  192. char32_t res = 0;
  193. switch (next) {
  194. case 'b':
  195. res = 8;
  196. break;
  197. case 't':
  198. res = 9;
  199. break;
  200. case 'n':
  201. res = 10;
  202. break;
  203. case 'f':
  204. res = 12;
  205. break;
  206. case 'r':
  207. res = 13;
  208. break;
  209. case 'u': {
  210. // hex number
  211. for (int j = 0; j < 4; j++) {
  212. char32_t c = p_str[index + j + 1];
  213. if (c == 0) {
  214. r_err_str = "Unterminated String";
  215. return ERR_PARSE_ERROR;
  216. }
  217. if (!is_hex_digit(c)) {
  218. r_err_str = "Malformed hex constant in string";
  219. return ERR_PARSE_ERROR;
  220. }
  221. char32_t v;
  222. if (is_digit(c)) {
  223. v = c - '0';
  224. } else if (c >= 'a' && c <= 'f') {
  225. v = c - 'a';
  226. v += 10;
  227. } else if (c >= 'A' && c <= 'F') {
  228. v = c - 'A';
  229. v += 10;
  230. } else {
  231. ERR_PRINT("Bug parsing hex constant.");
  232. v = 0;
  233. }
  234. res <<= 4;
  235. res |= v;
  236. }
  237. index += 4; //will add at the end anyway
  238. if ((res & 0xfffffc00) == 0xd800) {
  239. if (p_str[index + 1] != '\\' || p_str[index + 2] != 'u') {
  240. r_err_str = "Invalid UTF-16 sequence in string, unpaired lead surrogate";
  241. return ERR_PARSE_ERROR;
  242. }
  243. index += 2;
  244. char32_t trail = 0;
  245. for (int j = 0; j < 4; j++) {
  246. char32_t c = p_str[index + j + 1];
  247. if (c == 0) {
  248. r_err_str = "Unterminated String";
  249. return ERR_PARSE_ERROR;
  250. }
  251. if (!is_hex_digit(c)) {
  252. r_err_str = "Malformed hex constant in string";
  253. return ERR_PARSE_ERROR;
  254. }
  255. char32_t v;
  256. if (is_digit(c)) {
  257. v = c - '0';
  258. } else if (c >= 'a' && c <= 'f') {
  259. v = c - 'a';
  260. v += 10;
  261. } else if (c >= 'A' && c <= 'F') {
  262. v = c - 'A';
  263. v += 10;
  264. } else {
  265. ERR_PRINT("Bug parsing hex constant.");
  266. v = 0;
  267. }
  268. trail <<= 4;
  269. trail |= v;
  270. }
  271. if ((trail & 0xfffffc00) == 0xdc00) {
  272. res = (res << 10UL) + trail - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  273. index += 4; //will add at the end anyway
  274. } else {
  275. r_err_str = "Invalid UTF-16 sequence in string, unpaired lead surrogate";
  276. return ERR_PARSE_ERROR;
  277. }
  278. } else if ((res & 0xfffffc00) == 0xdc00) {
  279. r_err_str = "Invalid UTF-16 sequence in string, unpaired trail surrogate";
  280. return ERR_PARSE_ERROR;
  281. }
  282. } break;
  283. default: {
  284. res = next;
  285. } break;
  286. }
  287. str += res;
  288. } else {
  289. if (p_str[index] == '\n') {
  290. line++;
  291. }
  292. str += p_str[index];
  293. }
  294. index++;
  295. }
  296. r_token.type = TK_STRING;
  297. r_token.value = str;
  298. return OK;
  299. } break;
  300. default: {
  301. if (p_str[index] <= 32) {
  302. index++;
  303. break;
  304. }
  305. if (p_str[index] == '-' || is_digit(p_str[index])) {
  306. //a number
  307. const char32_t *rptr;
  308. double number = String::to_float(&p_str[index], &rptr);
  309. index += (rptr - &p_str[index]);
  310. r_token.type = TK_NUMBER;
  311. r_token.value = number;
  312. return OK;
  313. } else if (is_ascii_char(p_str[index])) {
  314. String id;
  315. while (is_ascii_char(p_str[index])) {
  316. id += p_str[index];
  317. index++;
  318. }
  319. r_token.type = TK_IDENTIFIER;
  320. r_token.value = id;
  321. return OK;
  322. } else {
  323. r_err_str = "Unexpected character.";
  324. return ERR_PARSE_ERROR;
  325. }
  326. }
  327. }
  328. }
  329. return ERR_PARSE_ERROR;
  330. }
  331. Error JSON::_parse_value(Variant &value, Token &token, const char32_t *p_str, int &index, int p_len, int &line, int p_depth, String &r_err_str) {
  332. if (p_depth > Variant::MAX_RECURSION_DEPTH) {
  333. r_err_str = "JSON structure is too deep. Bailing.";
  334. return ERR_OUT_OF_MEMORY;
  335. }
  336. if (token.type == TK_CURLY_BRACKET_OPEN) {
  337. Dictionary d;
  338. Error err = _parse_object(d, p_str, index, p_len, line, p_depth + 1, r_err_str);
  339. if (err) {
  340. return err;
  341. }
  342. value = d;
  343. } else if (token.type == TK_BRACKET_OPEN) {
  344. Array a;
  345. Error err = _parse_array(a, p_str, index, p_len, line, p_depth + 1, r_err_str);
  346. if (err) {
  347. return err;
  348. }
  349. value = a;
  350. } else if (token.type == TK_IDENTIFIER) {
  351. String id = token.value;
  352. if (id == "true") {
  353. value = true;
  354. } else if (id == "false") {
  355. value = false;
  356. } else if (id == "null") {
  357. value = Variant();
  358. } else {
  359. r_err_str = "Expected 'true','false' or 'null', got '" + id + "'.";
  360. return ERR_PARSE_ERROR;
  361. }
  362. } else if (token.type == TK_NUMBER) {
  363. value = token.value;
  364. } else if (token.type == TK_STRING) {
  365. value = token.value;
  366. } else {
  367. r_err_str = "Expected value, got " + String(tk_name[token.type]) + ".";
  368. return ERR_PARSE_ERROR;
  369. }
  370. return OK;
  371. }
  372. Error JSON::_parse_array(Array &array, const char32_t *p_str, int &index, int p_len, int &line, int p_depth, String &r_err_str) {
  373. Token token;
  374. bool need_comma = false;
  375. while (index < p_len) {
  376. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  377. if (err != OK) {
  378. return err;
  379. }
  380. if (token.type == TK_BRACKET_CLOSE) {
  381. return OK;
  382. }
  383. if (need_comma) {
  384. if (token.type != TK_COMMA) {
  385. r_err_str = "Expected ','";
  386. return ERR_PARSE_ERROR;
  387. } else {
  388. need_comma = false;
  389. continue;
  390. }
  391. }
  392. Variant v;
  393. err = _parse_value(v, token, p_str, index, p_len, line, p_depth, r_err_str);
  394. if (err) {
  395. return err;
  396. }
  397. array.push_back(v);
  398. need_comma = true;
  399. }
  400. r_err_str = "Expected ']'";
  401. return ERR_PARSE_ERROR;
  402. }
  403. Error JSON::_parse_object(Dictionary &object, const char32_t *p_str, int &index, int p_len, int &line, int p_depth, String &r_err_str) {
  404. bool at_key = true;
  405. String key;
  406. Token token;
  407. bool need_comma = false;
  408. while (index < p_len) {
  409. if (at_key) {
  410. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  411. if (err != OK) {
  412. return err;
  413. }
  414. if (token.type == TK_CURLY_BRACKET_CLOSE) {
  415. return OK;
  416. }
  417. if (need_comma) {
  418. if (token.type != TK_COMMA) {
  419. r_err_str = "Expected '}' or ','";
  420. return ERR_PARSE_ERROR;
  421. } else {
  422. need_comma = false;
  423. continue;
  424. }
  425. }
  426. if (token.type != TK_STRING) {
  427. r_err_str = "Expected key";
  428. return ERR_PARSE_ERROR;
  429. }
  430. key = token.value;
  431. err = _get_token(p_str, index, p_len, token, line, r_err_str);
  432. if (err != OK) {
  433. return err;
  434. }
  435. if (token.type != TK_COLON) {
  436. r_err_str = "Expected ':'";
  437. return ERR_PARSE_ERROR;
  438. }
  439. at_key = false;
  440. } else {
  441. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  442. if (err != OK) {
  443. return err;
  444. }
  445. Variant v;
  446. err = _parse_value(v, token, p_str, index, p_len, line, p_depth, r_err_str);
  447. if (err) {
  448. return err;
  449. }
  450. object[key] = v;
  451. need_comma = true;
  452. at_key = true;
  453. }
  454. }
  455. r_err_str = "Expected '}'";
  456. return ERR_PARSE_ERROR;
  457. }
  458. void JSON::set_data(const Variant &p_data) {
  459. data = p_data;
  460. }
  461. Error JSON::_parse_string(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line) {
  462. const char32_t *str = p_json.ptr();
  463. int idx = 0;
  464. int len = p_json.length();
  465. Token token;
  466. r_err_line = 0;
  467. String aux_key;
  468. Error err = _get_token(str, idx, len, token, r_err_line, r_err_str);
  469. if (err) {
  470. return err;
  471. }
  472. err = _parse_value(r_ret, token, str, idx, len, r_err_line, 0, r_err_str);
  473. // Check if EOF is reached
  474. // or it's a type of the next token.
  475. if (err == OK && idx < len) {
  476. err = _get_token(str, idx, len, token, r_err_line, r_err_str);
  477. if (err || token.type != TK_EOF) {
  478. r_err_str = "Expected 'EOF'";
  479. // Reset return value to empty `Variant`
  480. r_ret = Variant();
  481. return ERR_PARSE_ERROR;
  482. }
  483. }
  484. return err;
  485. }
  486. Error JSON::parse(const String &p_json_string) {
  487. Error err = _parse_string(p_json_string, data, err_str, err_line);
  488. if (err == Error::OK) {
  489. err_line = 0;
  490. }
  491. return err;
  492. }
  493. String JSON::stringify(const Variant &p_var, const String &p_indent, bool p_sort_keys, bool p_full_precision) {
  494. Ref<JSON> jason;
  495. jason.instantiate();
  496. HashSet<const void *> markers;
  497. return jason->_stringify(p_var, p_indent, 0, p_sort_keys, markers, p_full_precision);
  498. }
  499. Variant JSON::parse_string(const String &p_json_string) {
  500. Ref<JSON> jason;
  501. jason.instantiate();
  502. Error error = jason->parse(p_json_string);
  503. ERR_FAIL_COND_V_MSG(error != Error::OK, Variant(), vformat("Parse JSON failed. Error at line %d: %s", jason->get_error_line(), jason->get_error_message()));
  504. return jason->get_data();
  505. }
  506. void JSON::_bind_methods() {
  507. ClassDB::bind_static_method("JSON", D_METHOD("stringify", "data", "indent", "sort_keys", "full_precision"), &JSON::stringify, DEFVAL(""), DEFVAL(true), DEFVAL(false));
  508. ClassDB::bind_static_method("JSON", D_METHOD("parse_string", "json_string"), &JSON::parse_string);
  509. ClassDB::bind_method(D_METHOD("parse", "json_string"), &JSON::parse);
  510. ClassDB::bind_method(D_METHOD("get_data"), &JSON::get_data);
  511. ClassDB::bind_method(D_METHOD("set_data", "data"), &JSON::set_data);
  512. ClassDB::bind_method(D_METHOD("get_error_line"), &JSON::get_error_line);
  513. ClassDB::bind_method(D_METHOD("get_error_message"), &JSON::get_error_message);
  514. ADD_PROPERTY(PropertyInfo(Variant::NIL, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT), "set_data", "get_data"); // Ensures that it can be serialized as binary.
  515. }
  516. ////
  517. ////////////
  518. Ref<Resource> ResourceFormatLoaderJSON::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  519. if (r_error) {
  520. *r_error = ERR_FILE_CANT_OPEN;
  521. }
  522. if (!FileAccess::exists(p_path)) {
  523. *r_error = ERR_FILE_NOT_FOUND;
  524. return Ref<Resource>();
  525. }
  526. Ref<JSON> json;
  527. json.instantiate();
  528. Error err = json->parse(FileAccess::get_file_as_string(p_path));
  529. if (err != OK) {
  530. if (r_error) {
  531. *r_error = err;
  532. }
  533. ERR_PRINT("Error parsing JSON file at '" + p_path + "', on line " + itos(json->get_error_line()) + ": " + json->get_error_message());
  534. return Ref<Resource>();
  535. }
  536. if (r_error) {
  537. *r_error = OK;
  538. }
  539. return json;
  540. }
  541. void ResourceFormatLoaderJSON::get_recognized_extensions(List<String> *p_extensions) const {
  542. p_extensions->push_back("json");
  543. }
  544. bool ResourceFormatLoaderJSON::handles_type(const String &p_type) const {
  545. return (p_type == "JSON");
  546. }
  547. String ResourceFormatLoaderJSON::get_resource_type(const String &p_path) const {
  548. String el = p_path.get_extension().to_lower();
  549. if (el == "json") {
  550. return "JSON";
  551. }
  552. return "";
  553. }
  554. Error ResourceFormatSaverJSON::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  555. Ref<JSON> json = p_resource;
  556. ERR_FAIL_COND_V(json.is_null(), ERR_INVALID_PARAMETER);
  557. String source = JSON::stringify(json->get_data(), "\t", false, true);
  558. Error err;
  559. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  560. ERR_FAIL_COND_V_MSG(err, err, "Cannot save json '" + p_path + "'.");
  561. file->store_string(source);
  562. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  563. return ERR_CANT_CREATE;
  564. }
  565. return OK;
  566. }
  567. void ResourceFormatSaverJSON::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  568. Ref<JSON> json = p_resource;
  569. if (json.is_valid()) {
  570. p_extensions->push_back("json");
  571. }
  572. }
  573. bool ResourceFormatSaverJSON::recognize(const Ref<Resource> &p_resource) const {
  574. return p_resource->get_class_name() == "JSON"; //only json, not inherited
  575. }