json.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. String colon = ":";
  55. String end_statement = "";
  56. if (!p_indent.is_empty()) {
  57. colon += " ";
  58. end_statement += "\n";
  59. }
  60. switch (p_var.get_type()) {
  61. case Variant::NIL:
  62. return "null";
  63. case Variant::BOOL:
  64. return p_var.operator bool() ? "true" : "false";
  65. case Variant::INT:
  66. return itos(p_var);
  67. case Variant::FLOAT: {
  68. double num = p_var;
  69. if (p_full_precision) {
  70. // Store unreliable digits (17) instead of just reliable
  71. // digits (14) so that the value can be decoded exactly.
  72. return String::num(num, 17 - (int)floor(log10(num)));
  73. } else {
  74. // Store only reliable digits (14) by default.
  75. return String::num(num, 14 - (int)floor(log10(num)));
  76. }
  77. }
  78. case Variant::PACKED_INT32_ARRAY:
  79. case Variant::PACKED_INT64_ARRAY:
  80. case Variant::PACKED_FLOAT32_ARRAY:
  81. case Variant::PACKED_FLOAT64_ARRAY:
  82. case Variant::PACKED_STRING_ARRAY:
  83. case Variant::ARRAY: {
  84. String s = "[";
  85. s += end_statement;
  86. Array a = p_var;
  87. ERR_FAIL_COND_V_MSG(p_markers.has(a.id()), "\"[...]\"", "Converting circular structure to JSON.");
  88. p_markers.insert(a.id());
  89. for (int i = 0; i < a.size(); i++) {
  90. if (i > 0) {
  91. s += ",";
  92. s += end_statement;
  93. }
  94. s += _make_indent(p_indent, p_cur_indent + 1) + _stringify(a[i], p_indent, p_cur_indent + 1, p_sort_keys, p_markers);
  95. }
  96. s += end_statement + _make_indent(p_indent, p_cur_indent) + "]";
  97. p_markers.erase(a.id());
  98. return s;
  99. }
  100. case Variant::DICTIONARY: {
  101. String s = "{";
  102. s += end_statement;
  103. Dictionary d = p_var;
  104. ERR_FAIL_COND_V_MSG(p_markers.has(d.id()), "\"{...}\"", "Converting circular structure to JSON.");
  105. p_markers.insert(d.id());
  106. List<Variant> keys;
  107. d.get_key_list(&keys);
  108. if (p_sort_keys) {
  109. keys.sort();
  110. }
  111. bool first_key = true;
  112. for (const Variant &E : keys) {
  113. if (first_key) {
  114. first_key = false;
  115. } else {
  116. s += ",";
  117. s += end_statement;
  118. }
  119. s += _make_indent(p_indent, p_cur_indent + 1) + _stringify(String(E), p_indent, p_cur_indent + 1, p_sort_keys, p_markers);
  120. s += colon;
  121. s += _stringify(d[E], p_indent, p_cur_indent + 1, p_sort_keys, p_markers);
  122. }
  123. s += end_statement + _make_indent(p_indent, p_cur_indent) + "}";
  124. p_markers.erase(d.id());
  125. return s;
  126. }
  127. default:
  128. return "\"" + String(p_var).json_escape() + "\"";
  129. }
  130. }
  131. Error JSON::_get_token(const char32_t *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str) {
  132. while (p_len > 0) {
  133. switch (p_str[index]) {
  134. case '\n': {
  135. line++;
  136. index++;
  137. break;
  138. }
  139. case 0: {
  140. r_token.type = TK_EOF;
  141. return OK;
  142. } break;
  143. case '{': {
  144. r_token.type = TK_CURLY_BRACKET_OPEN;
  145. index++;
  146. return OK;
  147. }
  148. case '}': {
  149. r_token.type = TK_CURLY_BRACKET_CLOSE;
  150. index++;
  151. return OK;
  152. }
  153. case '[': {
  154. r_token.type = TK_BRACKET_OPEN;
  155. index++;
  156. return OK;
  157. }
  158. case ']': {
  159. r_token.type = TK_BRACKET_CLOSE;
  160. index++;
  161. return OK;
  162. }
  163. case ':': {
  164. r_token.type = TK_COLON;
  165. index++;
  166. return OK;
  167. }
  168. case ',': {
  169. r_token.type = TK_COMMA;
  170. index++;
  171. return OK;
  172. }
  173. case '"': {
  174. index++;
  175. String str;
  176. while (true) {
  177. if (p_str[index] == 0) {
  178. r_err_str = "Unterminated String";
  179. return ERR_PARSE_ERROR;
  180. } else if (p_str[index] == '"') {
  181. index++;
  182. break;
  183. } else if (p_str[index] == '\\') {
  184. //escaped characters...
  185. index++;
  186. char32_t next = p_str[index];
  187. if (next == 0) {
  188. r_err_str = "Unterminated String";
  189. return ERR_PARSE_ERROR;
  190. }
  191. char32_t res = 0;
  192. switch (next) {
  193. case 'b':
  194. res = 8;
  195. break;
  196. case 't':
  197. res = 9;
  198. break;
  199. case 'n':
  200. res = 10;
  201. break;
  202. case 'f':
  203. res = 12;
  204. break;
  205. case 'r':
  206. res = 13;
  207. break;
  208. case 'u': {
  209. // hex number
  210. for (int j = 0; j < 4; j++) {
  211. char32_t c = p_str[index + j + 1];
  212. if (c == 0) {
  213. r_err_str = "Unterminated String";
  214. return ERR_PARSE_ERROR;
  215. }
  216. if (!is_hex_digit(c)) {
  217. r_err_str = "Malformed hex constant in string";
  218. return ERR_PARSE_ERROR;
  219. }
  220. char32_t v;
  221. if (is_digit(c)) {
  222. v = c - '0';
  223. } else if (c >= 'a' && c <= 'f') {
  224. v = c - 'a';
  225. v += 10;
  226. } else if (c >= 'A' && c <= 'F') {
  227. v = c - 'A';
  228. v += 10;
  229. } else {
  230. ERR_PRINT("Bug parsing hex constant.");
  231. v = 0;
  232. }
  233. res <<= 4;
  234. res |= v;
  235. }
  236. index += 4; //will add at the end anyway
  237. if ((res & 0xfffffc00) == 0xd800) {
  238. if (p_str[index + 1] != '\\' || p_str[index + 2] != 'u') {
  239. r_err_str = "Invalid UTF-16 sequence in string, unpaired lead surrogate";
  240. return ERR_PARSE_ERROR;
  241. }
  242. index += 2;
  243. char32_t trail = 0;
  244. for (int j = 0; j < 4; j++) {
  245. char32_t c = p_str[index + j + 1];
  246. if (c == 0) {
  247. r_err_str = "Unterminated String";
  248. return ERR_PARSE_ERROR;
  249. }
  250. if (!is_hex_digit(c)) {
  251. r_err_str = "Malformed hex constant in string";
  252. return ERR_PARSE_ERROR;
  253. }
  254. char32_t v;
  255. if (is_digit(c)) {
  256. v = c - '0';
  257. } else if (c >= 'a' && c <= 'f') {
  258. v = c - 'a';
  259. v += 10;
  260. } else if (c >= 'A' && c <= 'F') {
  261. v = c - 'A';
  262. v += 10;
  263. } else {
  264. ERR_PRINT("Bug parsing hex constant.");
  265. v = 0;
  266. }
  267. trail <<= 4;
  268. trail |= v;
  269. }
  270. if ((trail & 0xfffffc00) == 0xdc00) {
  271. res = (res << 10UL) + trail - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  272. index += 4; //will add at the end anyway
  273. } else {
  274. r_err_str = "Invalid UTF-16 sequence in string, unpaired lead surrogate";
  275. return ERR_PARSE_ERROR;
  276. }
  277. } else if ((res & 0xfffffc00) == 0xdc00) {
  278. r_err_str = "Invalid UTF-16 sequence in string, unpaired trail surrogate";
  279. return ERR_PARSE_ERROR;
  280. }
  281. } break;
  282. default: {
  283. res = next;
  284. } break;
  285. }
  286. str += res;
  287. } else {
  288. if (p_str[index] == '\n') {
  289. line++;
  290. }
  291. str += p_str[index];
  292. }
  293. index++;
  294. }
  295. r_token.type = TK_STRING;
  296. r_token.value = str;
  297. return OK;
  298. } break;
  299. default: {
  300. if (p_str[index] <= 32) {
  301. index++;
  302. break;
  303. }
  304. if (p_str[index] == '-' || is_digit(p_str[index])) {
  305. //a number
  306. const char32_t *rptr;
  307. double number = String::to_float(&p_str[index], &rptr);
  308. index += (rptr - &p_str[index]);
  309. r_token.type = TK_NUMBER;
  310. r_token.value = number;
  311. return OK;
  312. } else if (is_ascii_char(p_str[index])) {
  313. String id;
  314. while (is_ascii_char(p_str[index])) {
  315. id += p_str[index];
  316. index++;
  317. }
  318. r_token.type = TK_IDENTIFIER;
  319. r_token.value = id;
  320. return OK;
  321. } else {
  322. r_err_str = "Unexpected character.";
  323. return ERR_PARSE_ERROR;
  324. }
  325. }
  326. }
  327. }
  328. return ERR_PARSE_ERROR;
  329. }
  330. Error JSON::_parse_value(Variant &value, Token &token, const char32_t *p_str, int &index, int p_len, int &line, String &r_err_str) {
  331. if (token.type == TK_CURLY_BRACKET_OPEN) {
  332. Dictionary d;
  333. Error err = _parse_object(d, p_str, index, p_len, line, r_err_str);
  334. if (err) {
  335. return err;
  336. }
  337. value = d;
  338. } else if (token.type == TK_BRACKET_OPEN) {
  339. Array a;
  340. Error err = _parse_array(a, p_str, index, p_len, line, r_err_str);
  341. if (err) {
  342. return err;
  343. }
  344. value = a;
  345. } else if (token.type == TK_IDENTIFIER) {
  346. String id = token.value;
  347. if (id == "true") {
  348. value = true;
  349. } else if (id == "false") {
  350. value = false;
  351. } else if (id == "null") {
  352. value = Variant();
  353. } else {
  354. r_err_str = "Expected 'true','false' or 'null', got '" + id + "'.";
  355. return ERR_PARSE_ERROR;
  356. }
  357. } else if (token.type == TK_NUMBER) {
  358. value = token.value;
  359. } else if (token.type == TK_STRING) {
  360. value = token.value;
  361. } else {
  362. r_err_str = "Expected value, got " + String(tk_name[token.type]) + ".";
  363. return ERR_PARSE_ERROR;
  364. }
  365. return OK;
  366. }
  367. Error JSON::_parse_array(Array &array, const char32_t *p_str, int &index, int p_len, int &line, String &r_err_str) {
  368. Token token;
  369. bool need_comma = false;
  370. while (index < p_len) {
  371. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  372. if (err != OK) {
  373. return err;
  374. }
  375. if (token.type == TK_BRACKET_CLOSE) {
  376. return OK;
  377. }
  378. if (need_comma) {
  379. if (token.type != TK_COMMA) {
  380. r_err_str = "Expected ','";
  381. return ERR_PARSE_ERROR;
  382. } else {
  383. need_comma = false;
  384. continue;
  385. }
  386. }
  387. Variant v;
  388. err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
  389. if (err) {
  390. return err;
  391. }
  392. array.push_back(v);
  393. need_comma = true;
  394. }
  395. r_err_str = "Expected ']'";
  396. return ERR_PARSE_ERROR;
  397. }
  398. Error JSON::_parse_object(Dictionary &object, const char32_t *p_str, int &index, int p_len, int &line, String &r_err_str) {
  399. bool at_key = true;
  400. String key;
  401. Token token;
  402. bool need_comma = false;
  403. while (index < p_len) {
  404. if (at_key) {
  405. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  406. if (err != OK) {
  407. return err;
  408. }
  409. if (token.type == TK_CURLY_BRACKET_CLOSE) {
  410. return OK;
  411. }
  412. if (need_comma) {
  413. if (token.type != TK_COMMA) {
  414. r_err_str = "Expected '}' or ','";
  415. return ERR_PARSE_ERROR;
  416. } else {
  417. need_comma = false;
  418. continue;
  419. }
  420. }
  421. if (token.type != TK_STRING) {
  422. r_err_str = "Expected key";
  423. return ERR_PARSE_ERROR;
  424. }
  425. key = token.value;
  426. err = _get_token(p_str, index, p_len, token, line, r_err_str);
  427. if (err != OK) {
  428. return err;
  429. }
  430. if (token.type != TK_COLON) {
  431. r_err_str = "Expected ':'";
  432. return ERR_PARSE_ERROR;
  433. }
  434. at_key = false;
  435. } else {
  436. Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
  437. if (err != OK) {
  438. return err;
  439. }
  440. Variant v;
  441. err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
  442. if (err) {
  443. return err;
  444. }
  445. object[key] = v;
  446. need_comma = true;
  447. at_key = true;
  448. }
  449. }
  450. r_err_str = "Expected '}'";
  451. return ERR_PARSE_ERROR;
  452. }
  453. void JSON::set_data(const Variant &p_data) {
  454. data = p_data;
  455. }
  456. Error JSON::_parse_string(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line) {
  457. const char32_t *str = p_json.ptr();
  458. int idx = 0;
  459. int len = p_json.length();
  460. Token token;
  461. r_err_line = 0;
  462. String aux_key;
  463. Error err = _get_token(str, idx, len, token, r_err_line, r_err_str);
  464. if (err) {
  465. return err;
  466. }
  467. err = _parse_value(r_ret, token, str, idx, len, r_err_line, r_err_str);
  468. // Check if EOF is reached
  469. // or it's a type of the next token.
  470. if (err == OK && idx < len) {
  471. err = _get_token(str, idx, len, token, r_err_line, r_err_str);
  472. if (err || token.type != TK_EOF) {
  473. r_err_str = "Expected 'EOF'";
  474. // Reset return value to empty `Variant`
  475. r_ret = Variant();
  476. return ERR_PARSE_ERROR;
  477. }
  478. }
  479. return err;
  480. }
  481. Error JSON::parse(const String &p_json_string) {
  482. Error err = _parse_string(p_json_string, data, err_str, err_line);
  483. if (err == Error::OK) {
  484. err_line = 0;
  485. }
  486. return err;
  487. }
  488. String JSON::stringify(const Variant &p_var, const String &p_indent, bool p_sort_keys, bool p_full_precision) {
  489. Ref<JSON> jason;
  490. jason.instantiate();
  491. HashSet<const void *> markers;
  492. return jason->_stringify(p_var, p_indent, 0, p_sort_keys, markers, p_full_precision);
  493. }
  494. Variant JSON::parse_string(const String &p_json_string) {
  495. Ref<JSON> jason;
  496. jason.instantiate();
  497. Error error = jason->parse(p_json_string);
  498. 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()));
  499. return jason->get_data();
  500. }
  501. void JSON::_bind_methods() {
  502. ClassDB::bind_static_method("JSON", D_METHOD("stringify", "data", "indent", "sort_keys", "full_precision"), &JSON::stringify, DEFVAL(""), DEFVAL(true), DEFVAL(false));
  503. ClassDB::bind_static_method("JSON", D_METHOD("parse_string", "json_string"), &JSON::parse_string);
  504. ClassDB::bind_method(D_METHOD("parse", "json_string"), &JSON::parse);
  505. ClassDB::bind_method(D_METHOD("get_data"), &JSON::get_data);
  506. ClassDB::bind_method(D_METHOD("set_data", "data"), &JSON::set_data);
  507. ClassDB::bind_method(D_METHOD("get_error_line"), &JSON::get_error_line);
  508. ClassDB::bind_method(D_METHOD("get_error_message"), &JSON::get_error_message);
  509. 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.
  510. }
  511. ////
  512. ////////////
  513. 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) {
  514. if (r_error) {
  515. *r_error = ERR_FILE_CANT_OPEN;
  516. }
  517. if (!FileAccess::exists(p_path)) {
  518. *r_error = ERR_FILE_NOT_FOUND;
  519. return Ref<Resource>();
  520. }
  521. Ref<JSON> json;
  522. json.instantiate();
  523. Error err = json->parse(FileAccess::get_file_as_string(p_path));
  524. if (err != OK) {
  525. if (r_error) {
  526. *r_error = err;
  527. }
  528. ERR_PRINT("Error parsing JSON file at '" + p_path + "', on line " + itos(json->get_error_line()) + ": " + json->get_error_message());
  529. return Ref<Resource>();
  530. }
  531. if (r_error) {
  532. *r_error = OK;
  533. }
  534. return json;
  535. }
  536. void ResourceFormatLoaderJSON::get_recognized_extensions(List<String> *p_extensions) const {
  537. p_extensions->push_back("json");
  538. }
  539. bool ResourceFormatLoaderJSON::handles_type(const String &p_type) const {
  540. return (p_type == "JSON");
  541. }
  542. String ResourceFormatLoaderJSON::get_resource_type(const String &p_path) const {
  543. String el = p_path.get_extension().to_lower();
  544. if (el == "json") {
  545. return "JSON";
  546. }
  547. return "";
  548. }
  549. Error ResourceFormatSaverJSON::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  550. Ref<JSON> json = p_resource;
  551. ERR_FAIL_COND_V(json.is_null(), ERR_INVALID_PARAMETER);
  552. String source = JSON::stringify(json->get_data(), "\t", false, true);
  553. Error err;
  554. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  555. ERR_FAIL_COND_V_MSG(err, err, "Cannot save json '" + p_path + "'.");
  556. file->store_string(source);
  557. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  558. return ERR_CANT_CREATE;
  559. }
  560. return OK;
  561. }
  562. void ResourceFormatSaverJSON::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  563. Ref<JSON> json = p_resource;
  564. if (json.is_valid()) {
  565. p_extensions->push_back("json");
  566. }
  567. }
  568. bool ResourceFormatSaverJSON::recognize(const Ref<Resource> &p_resource) const {
  569. return p_resource->get_class_name() == "JSON"; //only json, not inherited
  570. }