juce_JSON.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. class JSONParser
  22. {
  23. public:
  24. static Result parseObjectOrArray (String::CharPointerType t, var& result)
  25. {
  26. t = t.findEndOfWhitespace();
  27. switch (t.getAndAdvance())
  28. {
  29. case 0: result = var(); return Result::ok();
  30. case '{': return parseObject (t, result);
  31. case '[': return parseArray (t, result);
  32. }
  33. return createFail ("Expected '{' or '['", &t);
  34. }
  35. static Result parseString (const juce_wchar quoteChar, String::CharPointerType& t, var& result)
  36. {
  37. MemoryOutputStream buffer (256);
  38. for (;;)
  39. {
  40. juce_wchar c = t.getAndAdvance();
  41. if (c == quoteChar)
  42. break;
  43. if (c == '\\')
  44. {
  45. c = t.getAndAdvance();
  46. switch (c)
  47. {
  48. case '"':
  49. case '\'':
  50. case '\\':
  51. case '/': break;
  52. case 'a': c = '\a'; break;
  53. case 'b': c = '\b'; break;
  54. case 'f': c = '\f'; break;
  55. case 'n': c = '\n'; break;
  56. case 'r': c = '\r'; break;
  57. case 't': c = '\t'; break;
  58. case 'u':
  59. {
  60. c = 0;
  61. for (int i = 4; --i >= 0;)
  62. {
  63. const int digitValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  64. if (digitValue < 0)
  65. return createFail ("Syntax error in unicode escape sequence");
  66. c = (juce_wchar) ((c << 4) + digitValue);
  67. }
  68. break;
  69. }
  70. }
  71. }
  72. if (c == 0)
  73. return createFail ("Unexpected end-of-input in string constant");
  74. buffer.appendUTF8Char (c);
  75. }
  76. result = buffer.toUTF8();
  77. return Result::ok();
  78. }
  79. static Result parseAny (String::CharPointerType& t, var& result)
  80. {
  81. t = t.findEndOfWhitespace();
  82. String::CharPointerType t2 (t);
  83. switch (t2.getAndAdvance())
  84. {
  85. case '{': t = t2; return parseObject (t, result);
  86. case '[': t = t2; return parseArray (t, result);
  87. case '"': t = t2; return parseString ('"', t, result);
  88. case '\'': t = t2; return parseString ('\'', t, result);
  89. case '-':
  90. t2 = t2.findEndOfWhitespace();
  91. if (! CharacterFunctions::isDigit (*t2))
  92. break;
  93. t = t2;
  94. return parseNumber (t, result, true);
  95. case '0': case '1': case '2': case '3': case '4':
  96. case '5': case '6': case '7': case '8': case '9':
  97. return parseNumber (t, result, false);
  98. case 't': // "true"
  99. if (t2.getAndAdvance() == 'r' && t2.getAndAdvance() == 'u' && t2.getAndAdvance() == 'e')
  100. {
  101. t = t2;
  102. result = var (true);
  103. return Result::ok();
  104. }
  105. break;
  106. case 'f': // "false"
  107. if (t2.getAndAdvance() == 'a' && t2.getAndAdvance() == 'l'
  108. && t2.getAndAdvance() == 's' && t2.getAndAdvance() == 'e')
  109. {
  110. t = t2;
  111. result = var (false);
  112. return Result::ok();
  113. }
  114. break;
  115. case 'n': // "null"
  116. if (t2.getAndAdvance() == 'u' && t2.getAndAdvance() == 'l' && t2.getAndAdvance() == 'l')
  117. {
  118. t = t2;
  119. result = var();
  120. return Result::ok();
  121. }
  122. break;
  123. default:
  124. break;
  125. }
  126. return createFail ("Syntax error", &t);
  127. }
  128. private:
  129. static Result createFail (const char* const message, const String::CharPointerType* location = nullptr)
  130. {
  131. String m (message);
  132. if (location != nullptr)
  133. m << ": \"" << String (*location, 20) << '"';
  134. return Result::fail (m);
  135. }
  136. static Result parseNumber (String::CharPointerType& t, var& result, const bool isNegative)
  137. {
  138. String::CharPointerType oldT (t);
  139. int64 intValue = t.getAndAdvance() - '0';
  140. jassert (intValue >= 0 && intValue < 10);
  141. for (;;)
  142. {
  143. String::CharPointerType previousChar (t);
  144. const juce_wchar c = t.getAndAdvance();
  145. const int digit = ((int) c) - '0';
  146. if (isPositiveAndBelow (digit, 10))
  147. {
  148. intValue = intValue * 10 + digit;
  149. continue;
  150. }
  151. if (c == 'e' || c == 'E' || c == '.')
  152. {
  153. t = oldT;
  154. const double asDouble = CharacterFunctions::readDoubleValue (t);
  155. result = isNegative ? -asDouble : asDouble;
  156. return Result::ok();
  157. }
  158. if (CharacterFunctions::isWhitespace (c)
  159. || c == ',' || c == '}' || c == ']' || c == 0)
  160. {
  161. t = previousChar;
  162. break;
  163. }
  164. return createFail ("Syntax error in number", &oldT);
  165. }
  166. const int64 correctedValue = isNegative ? -intValue : intValue;
  167. if ((intValue >> 31) != 0)
  168. result = correctedValue;
  169. else
  170. result = (int) correctedValue;
  171. return Result::ok();
  172. }
  173. static Result parseObject (String::CharPointerType& t, var& result)
  174. {
  175. DynamicObject* const resultObject = new DynamicObject();
  176. result = resultObject;
  177. NamedValueSet& resultProperties = resultObject->getProperties();
  178. for (;;)
  179. {
  180. t = t.findEndOfWhitespace();
  181. String::CharPointerType oldT (t);
  182. const juce_wchar c = t.getAndAdvance();
  183. if (c == '}')
  184. break;
  185. if (c == 0)
  186. return createFail ("Unexpected end-of-input in object declaration");
  187. if (c == '"')
  188. {
  189. var propertyNameVar;
  190. Result r (parseString ('"', t, propertyNameVar));
  191. if (r.failed())
  192. return r;
  193. const Identifier propertyName (propertyNameVar.toString());
  194. if (propertyName.isValid())
  195. {
  196. t = t.findEndOfWhitespace();
  197. oldT = t;
  198. const juce_wchar c2 = t.getAndAdvance();
  199. if (c2 != ':')
  200. return createFail ("Expected ':', but found", &oldT);
  201. resultProperties.set (propertyName, var());
  202. var* propertyValue = resultProperties.getVarPointer (propertyName);
  203. Result r2 (parseAny (t, *propertyValue));
  204. if (r2.failed())
  205. return r2;
  206. t = t.findEndOfWhitespace();
  207. oldT = t;
  208. const juce_wchar nextChar = t.getAndAdvance();
  209. if (nextChar == ',')
  210. continue;
  211. if (nextChar == '}')
  212. break;
  213. }
  214. }
  215. return createFail ("Expected object member declaration, but found", &oldT);
  216. }
  217. return Result::ok();
  218. }
  219. static Result parseArray (String::CharPointerType& t, var& result)
  220. {
  221. result = var (Array<var>());
  222. Array<var>* const destArray = result.getArray();
  223. for (;;)
  224. {
  225. t = t.findEndOfWhitespace();
  226. String::CharPointerType oldT (t);
  227. const juce_wchar c = t.getAndAdvance();
  228. if (c == ']')
  229. break;
  230. if (c == 0)
  231. return createFail ("Unexpected end-of-input in array declaration");
  232. t = oldT;
  233. destArray->add (var());
  234. Result r (parseAny (t, destArray->getReference (destArray->size() - 1)));
  235. if (r.failed())
  236. return r;
  237. t = t.findEndOfWhitespace();
  238. oldT = t;
  239. const juce_wchar nextChar = t.getAndAdvance();
  240. if (nextChar == ',')
  241. continue;
  242. if (nextChar == ']')
  243. break;
  244. return createFail ("Expected object array item, but found", &oldT);
  245. }
  246. return Result::ok();
  247. }
  248. };
  249. //==============================================================================
  250. class JSONFormatter
  251. {
  252. public:
  253. static void write (OutputStream& out, const var& v,
  254. const int indentLevel, const bool allOnOneLine)
  255. {
  256. if (v.isString())
  257. {
  258. out << '"';
  259. writeString (out, v.toString().getCharPointer());
  260. out << '"';
  261. }
  262. else if (v.isVoid())
  263. {
  264. out << "null";
  265. }
  266. else if (v.isUndefined())
  267. {
  268. out << "undefined";
  269. }
  270. else if (v.isBool())
  271. {
  272. out << (static_cast<bool> (v) ? "true" : "false");
  273. }
  274. else if (v.isArray())
  275. {
  276. writeArray (out, *v.getArray(), indentLevel, allOnOneLine);
  277. }
  278. else if (v.isObject())
  279. {
  280. if (DynamicObject* object = v.getDynamicObject())
  281. object->writeAsJSON (out, indentLevel, allOnOneLine);
  282. else
  283. jassertfalse; // Only DynamicObjects can be converted to JSON!
  284. }
  285. else
  286. {
  287. // Can't convert these other types of object to JSON!
  288. jassert (! (v.isMethod() || v.isBinaryData()));
  289. out << v.toString();
  290. }
  291. }
  292. static void writeEscapedChar (OutputStream& out, const unsigned short value)
  293. {
  294. out << "\\u" << String::toHexString ((int) value).paddedLeft ('0', 4);
  295. }
  296. static void writeString (OutputStream& out, String::CharPointerType t)
  297. {
  298. for (;;)
  299. {
  300. const juce_wchar c (t.getAndAdvance());
  301. switch (c)
  302. {
  303. case 0: return;
  304. case '\"': out << "\\\""; break;
  305. case '\\': out << "\\\\"; break;
  306. case '\a': out << "\\a"; break;
  307. case '\b': out << "\\b"; break;
  308. case '\f': out << "\\f"; break;
  309. case '\t': out << "\\t"; break;
  310. case '\r': out << "\\r"; break;
  311. case '\n': out << "\\n"; break;
  312. default:
  313. if (c >= 32 && c < 127)
  314. {
  315. out << (char) c;
  316. }
  317. else
  318. {
  319. if (CharPointer_UTF16::getBytesRequiredFor (c) > 2)
  320. {
  321. CharPointer_UTF16::CharType chars[2];
  322. CharPointer_UTF16 utf16 (chars);
  323. utf16.write (c);
  324. for (int i = 0; i < 2; ++i)
  325. writeEscapedChar (out, (unsigned short) chars[i]);
  326. }
  327. else
  328. {
  329. writeEscapedChar (out, (unsigned short) c);
  330. }
  331. }
  332. break;
  333. }
  334. }
  335. }
  336. static void writeSpaces (OutputStream& out, int numSpaces)
  337. {
  338. out.writeRepeatedByte (' ', (size_t) numSpaces);
  339. }
  340. static void writeArray (OutputStream& out, const Array<var>& array,
  341. const int indentLevel, const bool allOnOneLine)
  342. {
  343. out << '[';
  344. if (array.size() > 0)
  345. {
  346. if (! allOnOneLine)
  347. out << newLine;
  348. for (int i = 0; i < array.size(); ++i)
  349. {
  350. if (! allOnOneLine)
  351. writeSpaces (out, indentLevel + indentSize);
  352. write (out, array.getReference(i), indentLevel + indentSize, allOnOneLine);
  353. if (i < array.size() - 1)
  354. {
  355. if (allOnOneLine)
  356. out << ", ";
  357. else
  358. out << ',' << newLine;
  359. }
  360. else if (! allOnOneLine)
  361. out << newLine;
  362. }
  363. if (! allOnOneLine)
  364. writeSpaces (out, indentLevel);
  365. }
  366. out << ']';
  367. }
  368. enum { indentSize = 2 };
  369. };
  370. //==============================================================================
  371. var JSON::parse (const String& text)
  372. {
  373. var result;
  374. if (! parse (text, result))
  375. result = var();
  376. return result;
  377. }
  378. var JSON::fromString (StringRef text)
  379. {
  380. var result;
  381. if (! JSONParser::parseAny (text.text, result))
  382. result = var();
  383. return result;
  384. }
  385. var JSON::parse (InputStream& input)
  386. {
  387. return parse (input.readEntireStreamAsString());
  388. }
  389. var JSON::parse (const File& file)
  390. {
  391. return parse (file.loadFileAsString());
  392. }
  393. Result JSON::parse (const String& text, var& result)
  394. {
  395. return JSONParser::parseObjectOrArray (text.getCharPointer(), result);
  396. }
  397. String JSON::toString (const var& data, const bool allOnOneLine)
  398. {
  399. MemoryOutputStream mo (1024);
  400. JSONFormatter::write (mo, data, 0, allOnOneLine);
  401. return mo.toUTF8();
  402. }
  403. void JSON::writeToStream (OutputStream& output, const var& data, const bool allOnOneLine)
  404. {
  405. JSONFormatter::write (output, data, 0, allOnOneLine);
  406. }
  407. String JSON::escapeString (StringRef s)
  408. {
  409. MemoryOutputStream mo;
  410. JSONFormatter::writeString (mo, s.text);
  411. return mo.toString();
  412. }
  413. Result JSON::parseQuotedString (String::CharPointerType& t, var& result)
  414. {
  415. const juce_wchar quote = t.getAndAdvance();
  416. if (quote == '"' || quote == '\'')
  417. return JSONParser::parseString (quote, t, result);
  418. return Result::fail ("Not a quoted string!");
  419. }
  420. //==============================================================================
  421. //==============================================================================
  422. #if JUCE_UNIT_TESTS
  423. class JSONTests : public UnitTest
  424. {
  425. public:
  426. JSONTests() : UnitTest ("JSON") {}
  427. static String createRandomWideCharString (Random& r)
  428. {
  429. juce_wchar buffer[40] = { 0 };
  430. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  431. {
  432. if (r.nextBool())
  433. {
  434. do
  435. {
  436. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  437. }
  438. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  439. }
  440. else
  441. buffer[i] = (juce_wchar) (1 + r.nextInt (0xff));
  442. }
  443. return CharPointer_UTF32 (buffer);
  444. }
  445. static String createRandomIdentifier (Random& r)
  446. {
  447. char buffer[30] = { 0 };
  448. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  449. {
  450. static const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-:";
  451. buffer[i] = chars [r.nextInt (sizeof (chars) - 1)];
  452. }
  453. return CharPointer_ASCII (buffer);
  454. }
  455. static var createRandomVar (Random& r, int depth)
  456. {
  457. switch (r.nextInt (depth > 3 ? 6 : 8))
  458. {
  459. case 0: return var();
  460. case 1: return r.nextInt();
  461. case 2: return r.nextInt64();
  462. case 3: return r.nextBool();
  463. case 4: return r.nextDouble();
  464. case 5: return createRandomWideCharString (r);
  465. case 6:
  466. {
  467. var v (createRandomVar (r, depth + 1));
  468. for (int i = 1 + r.nextInt (30); --i >= 0;)
  469. v.append (createRandomVar (r, depth + 1));
  470. return v;
  471. }
  472. case 7:
  473. {
  474. DynamicObject* o = new DynamicObject();
  475. for (int i = r.nextInt (30); --i >= 0;)
  476. o->setProperty (createRandomIdentifier (r), createRandomVar (r, depth + 1));
  477. return o;
  478. }
  479. default:
  480. return var();
  481. }
  482. }
  483. void runTest()
  484. {
  485. beginTest ("JSON");
  486. Random r = getRandom();
  487. expect (JSON::parse (String::empty) == var::null);
  488. expect (JSON::parse ("{}").isObject());
  489. expect (JSON::parse ("[]").isArray());
  490. expect (JSON::parse ("[ 1234 ]")[0].isInt());
  491. expect (JSON::parse ("[ 12345678901234 ]")[0].isInt64());
  492. expect (JSON::parse ("[ 1.123e3 ]")[0].isDouble());
  493. expect (JSON::parse ("[ -1234]")[0].isInt());
  494. expect (JSON::parse ("[-12345678901234]")[0].isInt64());
  495. expect (JSON::parse ("[-1.123e3]")[0].isDouble());
  496. for (int i = 100; --i >= 0;)
  497. {
  498. var v;
  499. if (i > 0)
  500. v = createRandomVar (r, 0);
  501. const bool oneLine = r.nextBool();
  502. String asString (JSON::toString (v, oneLine));
  503. var parsed = JSON::parse ("[" + asString + "]")[0];
  504. String parsedString (JSON::toString (parsed, oneLine));
  505. expect (asString.isNotEmpty() && parsedString == asString);
  506. }
  507. }
  508. };
  509. static JSONTests JSONUnitTests;
  510. #endif