json.cpp 18 KB

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