json.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. #include "json.h"
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <iostream>
  5. #include <cmath>
  6. #include <cfloat>
  7. #include <set>
  8. #include <regex>
  9. namespace json
  10. {
  11. Value Value::null;
  12. //constructors
  13. Value::Value()
  14. {
  15. type = Type::nullValue;
  16. value.objectValue = NULL;
  17. }
  18. Value::Value(Type type)
  19. {
  20. this->type = type;
  21. if (type == Type::stringValue)
  22. value.stringValue = new std::string();
  23. if (type == Type::arrayValue)
  24. value.arrayValue = new std::vector<Value>();
  25. if (type == Type::objectValue)
  26. value.objectValue = new std::map<std::string, Value>();
  27. }
  28. Value::Value(int value)
  29. {
  30. type = Type::intValue;
  31. this->value.intValue = value;
  32. }
  33. Value::Value(__int64 value)
  34. {
  35. //todo: value too big ?
  36. type = Type::intValue;
  37. this->value.intValue = value;
  38. }
  39. Value::Value(float value)
  40. {
  41. type = Type::floatValue;
  42. this->value.floatValue = value;
  43. }
  44. Value::Value(bool value)
  45. {
  46. type = Type::boolValue;
  47. this->value.boolValue = value;
  48. }
  49. Value::Value(const std::string &value)
  50. {
  51. type = Type::stringValue;
  52. this->value.stringValue = new std::string();
  53. this->value.stringValue->assign(value);
  54. }
  55. Value::Value(const char* value)
  56. {
  57. type = Type::stringValue;
  58. this->value.stringValue = new std::string();
  59. this->value.stringValue->assign(value);
  60. }
  61. Value::Value(const Value& other) : Value(other.type)
  62. {
  63. if (type == Type::objectValue)
  64. *this->value.objectValue = *other.value.objectValue;
  65. else if (type == Type::arrayValue)
  66. *this->value.arrayValue = *other.value.arrayValue;
  67. else if (type == Type::stringValue)
  68. this->value.stringValue->assign(*other.value.stringValue);
  69. else
  70. this->value = other.value;
  71. }
  72. void Value::operator=(const Value& other)
  73. {
  74. if (type != other.type)
  75. {
  76. if (type == Type::stringValue)
  77. delete value.stringValue;
  78. if (type == Type::arrayValue)
  79. delete value.arrayValue;
  80. if (type == Type::objectValue)
  81. delete value.objectValue;
  82. this->type = other.type;
  83. if (type == Type::stringValue)
  84. value.stringValue = new std::string();
  85. if (type == Type::arrayValue)
  86. value.arrayValue = new std::vector<Value>();
  87. if (type == Type::objectValue)
  88. value.objectValue = new std::map<std::string, Value>();
  89. }
  90. if (type == Type::objectValue)
  91. *this->value.objectValue = *other.value.objectValue;
  92. else if (type == Type::arrayValue)
  93. *this->value.arrayValue = *other.value.arrayValue;
  94. else if (type == Type::stringValue)
  95. this->value.stringValue->assign(*other.value.stringValue);
  96. else
  97. this->value = other.value;
  98. }
  99. Value::~Value()
  100. {
  101. if (type == Type::stringValue)
  102. delete value.stringValue;
  103. else if (type == Type::arrayValue)
  104. delete value.arrayValue;
  105. else if (type == Type::objectValue)
  106. delete value.objectValue;
  107. }
  108. size_t Value::size() const
  109. {
  110. assert(type == Type::arrayValue || type == Type::objectValue);
  111. if (type == Type::arrayValue)
  112. return value.arrayValue->size();
  113. else if (type == Type::objectValue)
  114. return value.objectValue->size();
  115. throw "Unsupported";
  116. }
  117. void Value::push_back(const Value& value)
  118. {
  119. assert(type == Type::arrayValue || type == Type::nullValue);
  120. if (type == Type::nullValue)
  121. {
  122. type = Type::arrayValue;
  123. this->value.arrayValue = new std::vector<Value>();
  124. }
  125. this->value.arrayValue->push_back(value);
  126. }
  127. Value& Value::operator[](const std::string &key)
  128. {
  129. assert(type == Type::objectValue || type == Type::nullValue);
  130. if (type == Type::nullValue)
  131. {
  132. type = Type::objectValue;
  133. value.objectValue = new std::map<std::string, Value>();
  134. }
  135. return (*value.objectValue)[key];
  136. }
  137. Value& Value::operator[](const std::string &key) const
  138. {
  139. assert(type == Type::objectValue);
  140. return (*value.objectValue)[key];
  141. }
  142. Value& Value::operator[](const char* key)
  143. {
  144. assert(type == Type::objectValue || type == Type::nullValue);
  145. if (type == Type::nullValue)
  146. {
  147. type = Type::objectValue;
  148. value.objectValue = new std::map<std::string, Value>();
  149. }
  150. return (*value.objectValue)[std::string(key)];
  151. }
  152. Value& Value::operator[](const char* key) const
  153. {
  154. assert(type == Type::objectValue);
  155. return (*value.objectValue)[std::string(key)];
  156. }
  157. Value& Value::operator[](size_t index)
  158. {
  159. assert(type == Type::arrayValue);
  160. return (*value.arrayValue)[index];
  161. }
  162. Value& Value::operator[](size_t index) const
  163. {
  164. assert(type == Type::arrayValue);
  165. return (*value.arrayValue)[index];
  166. }
  167. Value& Value::operator[](int index)
  168. {
  169. assert(type == Type::arrayValue);
  170. return (*value.arrayValue)[index];
  171. }
  172. Value& Value::operator[](int index) const
  173. {
  174. assert(type == Type::arrayValue);
  175. return (*value.arrayValue)[index];
  176. }
  177. void Value::erase(size_t index)
  178. {
  179. throw "Cannot cast";
  180. }
  181. Value::Iterator Value::end() const
  182. {
  183. if (type == Type::objectValue)
  184. return Iterator(value.objectValue->end());
  185. else if (type == Type::arrayValue)
  186. return Iterator(value.arrayValue->end());
  187. throw "oops";
  188. }
  189. Value::Iterator Value::begin() const
  190. {
  191. if (type == Type::objectValue)
  192. return Iterator(value.objectValue->begin());
  193. else if (type == Type::arrayValue)
  194. return Iterator(value.arrayValue->begin());
  195. throw "oops";
  196. }
  197. ///iterator stuff
  198. Value Value::Iterator::operator*()
  199. {
  200. if (type == Type::objectValue)
  201. return this->objectIterator->second;
  202. else if (type == Type::arrayValue)
  203. return *arrayIterator;
  204. throw "Oops";
  205. }
  206. bool Value::Iterator::operator!=(const Iterator &other)
  207. {
  208. if (type == Type::objectValue)
  209. return this->objectIterator != other.objectIterator;
  210. else if (type == Type::arrayValue)
  211. return this->arrayIterator != other.arrayIterator;
  212. throw "Oops";
  213. }
  214. void Value::Iterator::operator++()
  215. {
  216. if (type == Type::objectValue)
  217. this->objectIterator++;
  218. else if (type == Type::arrayValue)
  219. this->arrayIterator++;
  220. }
  221. void Value::Iterator::operator++(int)
  222. {
  223. if (type == Type::objectValue)
  224. this->objectIterator++;
  225. else if (type == Type::arrayValue)
  226. this->arrayIterator++;
  227. }
  228. Value::Iterator::Iterator(const std::vector<Value>::iterator& arrayIterator)
  229. {
  230. type = Type::arrayValue;
  231. this->arrayIterator = arrayIterator;
  232. }
  233. Value::Iterator::Iterator(const std::map<std::string, Value>::iterator& objectIterator)
  234. {
  235. type = Type::objectValue;
  236. this->objectIterator = objectIterator;
  237. }
  238. std::string Value::Iterator::key()
  239. {
  240. assert(type == Type::objectValue);
  241. return this->objectIterator->first;
  242. }
  243. Value& Value::Iterator::value()
  244. {
  245. assert(type == Type::objectValue);
  246. return this->objectIterator->second;
  247. }
  248. static int lineNumber;
  249. static void ltrim(std::istream& stream);
  250. static void eatComment(std::istream& stream);
  251. static Value eatString(std::istream& stream);
  252. static Value eatObject(std::istream& stream);
  253. static Value eatArray(std::istream& stream);
  254. static Value eatNumeric(std::istream& stream, char firstChar);
  255. static Value eatBool(std::istream& stream);
  256. static Value eatNull(std::istream& stream);
  257. static Value eatValue(std::istream& stream);
  258. //reading
  259. static void ltrim(std::istream& stream)
  260. {
  261. char c = stream.peek();
  262. while (c == ' ' || c == '\t' || c == '\n' || c == '\r')
  263. {
  264. if (c == '\n')
  265. lineNumber++;
  266. stream.get();
  267. c = stream.peek();
  268. }
  269. };
  270. static Value eatString(std::istream& stream)
  271. {
  272. std::string value = "";
  273. bool escaped = false;
  274. while (!stream.eof())
  275. {
  276. char c = stream.get();
  277. if (c == '\\' && !escaped)
  278. escaped = !escaped;
  279. else if (c == '\"' && !escaped)
  280. return Value(value);
  281. else
  282. {
  283. value += c;
  284. escaped = false;
  285. }
  286. }
  287. return Value(value);
  288. };
  289. static Value eatObject(std::istream& stream)
  290. {
  291. Value obj(Type::objectValue);
  292. while (!stream.eof())
  293. {
  294. ltrim(stream);
  295. char token = stream.get();
  296. if (token == '}')
  297. break; //empty object
  298. if (token == '/')
  299. {
  300. eatComment(stream);
  301. token = stream.get();
  302. }
  303. assert(token == '"');
  304. Value key = eatString(stream);
  305. ltrim(stream);
  306. token = stream.get();
  307. assert(token == ':');
  308. ltrim(stream);
  309. Value val = eatValue(stream);
  310. obj[key.asString()] = val;
  311. ltrim(stream);
  312. token = stream.get();
  313. if (token == '}')
  314. break;
  315. if (token != ',')
  316. throw "arg";
  317. assert(token == ',');
  318. }
  319. return obj;
  320. };
  321. static Value eatArray(std::istream& stream)
  322. {
  323. Value obj(Type::arrayValue);
  324. while (!stream.eof())
  325. {
  326. ltrim(stream);
  327. if (stream.peek() == ']')
  328. {
  329. stream.get();
  330. break;
  331. }
  332. obj.push_back(eatValue(stream));
  333. ltrim(stream);
  334. char token = stream.get();
  335. if (token == '/')
  336. {
  337. eatComment(stream);
  338. token = stream.get();
  339. }
  340. if (token == ']')
  341. break;
  342. assert(token == ',');
  343. }
  344. return obj;
  345. };
  346. static Value eatNumeric(std::istream& stream, char firstChar)
  347. {
  348. std::string numeric(1, firstChar);
  349. while (!stream.eof())
  350. {
  351. char token = stream.peek();
  352. if ((token >= '0' && token <= '9') || token == '.' || token == '-' || token == 'E')
  353. numeric += stream.get();
  354. else
  355. break;
  356. }
  357. if (numeric.find('.') == std::string::npos)
  358. return Value(atoi(numeric.c_str()));
  359. else
  360. return Value((float)atof(numeric.c_str()));
  361. };
  362. static Value eatBool(std::istream& stream)
  363. {
  364. char token = stream.get();
  365. if (token == 'a') //fAlse
  366. {
  367. stream.get(); //l
  368. stream.get(); //s
  369. stream.get(); //e
  370. return false;
  371. }
  372. else if (token == 'r') //tRue
  373. {
  374. stream.get(); // u
  375. stream.get(); // e
  376. return true;
  377. }
  378. return Value(Type::nullValue);
  379. };
  380. static Value eatNull(std::istream& stream)
  381. {
  382. stream.get(); // u
  383. stream.get(); // l
  384. stream.get(); // l
  385. return Value(Type::nullValue);
  386. };
  387. //precondition: / is already eaten
  388. static void eatComment(std::istream& stream)
  389. {
  390. char token = stream.get();
  391. assert(token == '/' || token == '*');
  392. if (token == '*')
  393. {
  394. char last = token;
  395. while ((last != '*' || token != '/') && !stream.eof())
  396. {
  397. last = token;
  398. token = stream.get();
  399. }
  400. }
  401. else if (token == '/')
  402. while (token != '\n' && !stream.eof())
  403. token = stream.get();
  404. ltrim(stream);
  405. }
  406. static Value eatValue(std::istream& stream)
  407. {
  408. ltrim(stream);
  409. char token = stream.get();
  410. if (token == '{')
  411. return eatObject(stream);
  412. if (token == '[')
  413. return eatArray(stream);
  414. if ((token >= '0' && token <= '9') || token == '.' || token == '-')
  415. return eatNumeric(stream, token);
  416. if (token == '"')
  417. return eatString(stream);
  418. if (token == 't' || token == 'f')
  419. return eatBool(stream);
  420. if (token == 'n')
  421. return eatNull(stream);
  422. if (token == '/')
  423. {
  424. eatComment(stream);
  425. return eatValue(stream);
  426. }
  427. throw "Unable to parse json";
  428. };
  429. Value readJson(const std::string &data)
  430. {
  431. std::stringstream stream;
  432. stream << data;
  433. lineNumber = 1;
  434. return eatValue(stream);
  435. }
  436. Value readJson(std::istream &stream)
  437. {
  438. assert(!stream.eof() && stream.good() && !stream.bad());
  439. lineNumber = 1;
  440. return eatValue(stream);
  441. }
  442. std::ostream& indent(std::ostream& stream, int level)
  443. {
  444. for (int i = 0; i < level; i++)
  445. stream << '\t';
  446. return stream;
  447. }
  448. std::ostream& Value::prettyPrint(std::ostream& stream, json::Value& printConfig, int level) const
  449. {
  450. stream << std::fixed << std::setprecision(6);
  451. switch (type)
  452. {
  453. case Type::intValue:
  454. stream << value.intValue;
  455. break;
  456. case Type::floatValue:
  457. assert(!isnan(value.floatValue));
  458. //assert(isnormal(value.floatValue));
  459. if (value.floatValue >= 0)
  460. stream << " ";
  461. stream << value.floatValue;
  462. break;
  463. case Type::boolValue:
  464. stream << (value.boolValue ? "true" : "false");
  465. break;
  466. case Type::stringValue:
  467. stream << "\"" << *value.stringValue << "\""; //TODO: escape \'s
  468. break;
  469. case Type::arrayValue:
  470. {
  471. stream << "[";
  472. int wrap = 99999;
  473. if (value.arrayValue->size() > 10)
  474. wrap = 1;
  475. if (value.arrayValue->at(0).isArray() || value.arrayValue->at(0).isObject())
  476. wrap = 1;
  477. else
  478. wrap = 3;
  479. std::string seperator = " ";
  480. if (!printConfig.isNull() && printConfig.isMember("wrap"))
  481. wrap = printConfig["wrap"];
  482. if (!printConfig.isNull() && printConfig.isMember("seperator"))
  483. seperator = printConfig["seperator"].asString();
  484. int index = 0;
  485. if ((long)size() > wrap)
  486. {
  487. stream << "\n";
  488. indent(stream, level + 1);
  489. }
  490. for (auto v : *this)
  491. {
  492. if (index > 0)
  493. {
  494. stream << "," << seperator;
  495. if (index % wrap == 0)
  496. {
  497. stream << "\n";
  498. indent(stream, level + 1);
  499. }
  500. }
  501. json::Value childPrintConfig = json::Value::null;
  502. if (!printConfig.isNull())
  503. {
  504. if (printConfig.isMember("elements"))
  505. childPrintConfig = printConfig["elements"];
  506. else if (printConfig.isMember("recursive") && printConfig["recursive"].asBool() == true)
  507. childPrintConfig = printConfig;
  508. }
  509. v.prettyPrint(stream, childPrintConfig, level + 1);
  510. index++;
  511. }
  512. if ((long)size() > wrap)
  513. {
  514. stream << "\n";
  515. indent(stream, level);
  516. }
  517. stream << "]";
  518. break;
  519. }
  520. case Type::objectValue:
  521. {
  522. stream << "{\n";
  523. int wrap = 99999;
  524. if (value.arrayValue->size() > 10)
  525. wrap = 1;
  526. if (value.arrayValue->at(0).isArray() || value.arrayValue->at(0).isObject())
  527. wrap = 1;
  528. else
  529. wrap = 3;
  530. std::string seperator = " ";
  531. if (!printConfig.isNull() && printConfig.isMember("wrap"))
  532. wrap = printConfig["wrap"];
  533. if (!printConfig.isNull() && printConfig.isMember("seperator"))
  534. seperator = printConfig["seperator"].asString();
  535. int index = 0;
  536. indent(stream, level + 1);
  537. //for (auto v : *value.objectValue)
  538. auto printEl = [&](const std::pair<const std::string&, const Value&> v)
  539. {
  540. if (index > 0)
  541. {
  542. stream << "," << seperator;
  543. if (index % wrap == 0)
  544. {
  545. stream << "\n";
  546. indent(stream, level + 1);
  547. }
  548. }
  549. stream << "\"" << v.first << "\" : ";
  550. if (
  551. (v.second.isArray() || v.second.isObject()) &&
  552. (printConfig.isNull() ||
  553. (
  554. printConfig.isMember(v.first) &&
  555. printConfig[v.first].isObject() &&
  556. printConfig[v.first].isMember("wrap") &&
  557. printConfig[v.first]["wrap"].asInt() < (int)v.second.size())
  558. )
  559. )
  560. {
  561. stream << "\n";
  562. indent(stream, level + 1);
  563. }
  564. json::Value childPrintConfig = json::Value::null;
  565. if (!printConfig.isNull())
  566. {
  567. if (printConfig.isMember(v.first))
  568. childPrintConfig = printConfig[v.first];
  569. else if (printConfig.isMember("recursive") && printConfig["recursive"].asBool() == true)
  570. childPrintConfig = printConfig;
  571. }
  572. v.second.prettyPrint(stream, childPrintConfig, level + 1);;
  573. index++;
  574. };
  575. std::set<std::string> printed;
  576. if (!printConfig.isNull())
  577. {
  578. if (printConfig.isMember("sort"))
  579. {
  580. for (std::string el : printConfig["sort"])
  581. {
  582. if (isMember(el))
  583. {
  584. printEl(std::pair<const std::string&, const Value&>(el, (*value.objectValue)[el]));
  585. printed.insert(el);
  586. }
  587. }
  588. }
  589. }
  590. for (auto v : *value.objectValue)
  591. if (printed.find(v.first) == printed.end())
  592. printEl(v);
  593. stream << "\n";
  594. indent(stream, level);
  595. stream << "}";
  596. break;
  597. }
  598. case Type::nullValue:
  599. stream << "null";
  600. break;
  601. }
  602. return stream;
  603. }
  604. const Value& Value::get(const char* key, const Value& default) const
  605. {
  606. if (isMember(key))
  607. return (*this)[key];
  608. return default;
  609. }
  610. std::string& operator <<(std::string &string, const Value& value)
  611. {
  612. std::stringstream stream;
  613. stream << value;
  614. string += stream.str();
  615. return string;
  616. }
  617. std::ostream & operator<<(std::ostream &stream, const Value& value)
  618. {
  619. stream << std::fixed << std::setprecision(6);
  620. switch (value.type)
  621. {
  622. case Type::intValue:
  623. stream << value.value.intValue;
  624. break;
  625. case Type::floatValue:
  626. assert(!isnan(value.value.floatValue));
  627. //assert(isnormal(value.value.floatValue));
  628. stream << value.value.floatValue;
  629. break;
  630. case Type::boolValue:
  631. stream << (value.value.boolValue ? "true" : "false");
  632. break;
  633. case Type::stringValue:
  634. {
  635. std::string escaped = *value.value.stringValue;
  636. escaped = std::regex_replace(escaped, std::regex("\\\\"), "\\\\");
  637. stream << "\"" << escaped << "\""; //TODO: escape \'s
  638. break;
  639. }
  640. case Type::arrayValue:
  641. {
  642. stream << "[";
  643. bool first = true;
  644. for (auto v : value)
  645. {
  646. if (!first)
  647. stream << ", ";
  648. stream << v;
  649. first = false;
  650. }
  651. stream << "]";
  652. break;
  653. }
  654. case Type::objectValue:
  655. {
  656. stream << "{";
  657. bool first = true;
  658. for (auto v : *value.value.objectValue)
  659. {
  660. if (!first)
  661. stream << ", ";
  662. stream << "\"" << v.first << "\" : " << v.second << std::endl;
  663. first = false;
  664. }
  665. stream << "}";
  666. break;
  667. }
  668. case Type::nullValue:
  669. stream << "null";
  670. break;
  671. }
  672. return stream;
  673. }
  674. }