json_pointer.hpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. #pragma once
  2. #include <algorithm> // all_of
  3. #include <cctype> // isdigit
  4. #include <limits> // max
  5. #include <numeric> // accumulate
  6. #include <string> // string
  7. #include <utility> // move
  8. #include <vector> // vector
  9. #include <nlohmann/detail/exceptions.hpp>
  10. #include <nlohmann/detail/macro_scope.hpp>
  11. #include <nlohmann/detail/string_escape.hpp>
  12. #include <nlohmann/detail/value_t.hpp>
  13. namespace nlohmann
  14. {
  15. /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
  16. /// @sa https://json.nlohmann.me/api/json_pointer/
  17. template<typename BasicJsonType>
  18. class json_pointer
  19. {
  20. // allow basic_json to access private members
  21. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  22. friend class basic_json;
  23. public:
  24. /// @brief create JSON pointer
  25. /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/
  26. explicit json_pointer(const std::string& s = "")
  27. : reference_tokens(split(s))
  28. {}
  29. /// @brief return a string representation of the JSON pointer
  30. /// @sa https://json.nlohmann.me/api/json_pointer/to_string/
  31. std::string to_string() const
  32. {
  33. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  34. std::string{},
  35. [](const std::string & a, const std::string & b)
  36. {
  37. return a + "/" + detail::escape(b);
  38. });
  39. }
  40. /// @brief return a string representation of the JSON pointer
  41. /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/
  42. operator std::string() const
  43. {
  44. return to_string();
  45. }
  46. /// @brief append another JSON pointer at the end of this JSON pointer
  47. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
  48. json_pointer& operator/=(const json_pointer& ptr)
  49. {
  50. reference_tokens.insert(reference_tokens.end(),
  51. ptr.reference_tokens.begin(),
  52. ptr.reference_tokens.end());
  53. return *this;
  54. }
  55. /// @brief append an unescaped reference token at the end of this JSON pointer
  56. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
  57. json_pointer& operator/=(std::string token)
  58. {
  59. push_back(std::move(token));
  60. return *this;
  61. }
  62. /// @brief append an array index at the end of this JSON pointer
  63. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/
  64. json_pointer& operator/=(std::size_t array_idx)
  65. {
  66. return *this /= std::to_string(array_idx);
  67. }
  68. /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  69. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
  70. friend json_pointer operator/(const json_pointer& lhs,
  71. const json_pointer& rhs)
  72. {
  73. return json_pointer(lhs) /= rhs;
  74. }
  75. /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  76. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
  77. friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param)
  78. {
  79. return json_pointer(lhs) /= std::move(token);
  80. }
  81. /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  82. /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/
  83. friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx)
  84. {
  85. return json_pointer(lhs) /= array_idx;
  86. }
  87. /// @brief returns the parent of this JSON pointer
  88. /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/
  89. json_pointer parent_pointer() const
  90. {
  91. if (empty())
  92. {
  93. return *this;
  94. }
  95. json_pointer res = *this;
  96. res.pop_back();
  97. return res;
  98. }
  99. /// @brief remove last reference token
  100. /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/
  101. void pop_back()
  102. {
  103. if (JSON_HEDLEY_UNLIKELY(empty()))
  104. {
  105. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  106. }
  107. reference_tokens.pop_back();
  108. }
  109. /// @brief return last reference token
  110. /// @sa https://json.nlohmann.me/api/json_pointer/back/
  111. const std::string& back() const
  112. {
  113. if (JSON_HEDLEY_UNLIKELY(empty()))
  114. {
  115. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  116. }
  117. return reference_tokens.back();
  118. }
  119. /// @brief append an unescaped token at the end of the reference pointer
  120. /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
  121. void push_back(const std::string& token)
  122. {
  123. reference_tokens.push_back(token);
  124. }
  125. /// @brief append an unescaped token at the end of the reference pointer
  126. /// @sa https://json.nlohmann.me/api/json_pointer/push_back/
  127. void push_back(std::string&& token)
  128. {
  129. reference_tokens.push_back(std::move(token));
  130. }
  131. /// @brief return whether pointer points to the root document
  132. /// @sa https://json.nlohmann.me/api/json_pointer/empty/
  133. bool empty() const noexcept
  134. {
  135. return reference_tokens.empty();
  136. }
  137. private:
  138. /*!
  139. @param[in] s reference token to be converted into an array index
  140. @return integer representation of @a s
  141. @throw parse_error.106 if an array index begins with '0'
  142. @throw parse_error.109 if an array index begins not with a digit
  143. @throw out_of_range.404 if string @a s could not be converted to an integer
  144. @throw out_of_range.410 if an array index exceeds size_type
  145. */
  146. static typename BasicJsonType::size_type array_index(const std::string& s)
  147. {
  148. using size_type = typename BasicJsonType::size_type;
  149. // error condition (cf. RFC 6901, Sect. 4)
  150. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
  151. {
  152. JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType()));
  153. }
  154. // error condition (cf. RFC 6901, Sect. 4)
  155. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
  156. {
  157. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType()));
  158. }
  159. std::size_t processed_chars = 0;
  160. unsigned long long res = 0; // NOLINT(runtime/int)
  161. JSON_TRY
  162. {
  163. res = std::stoull(s, &processed_chars);
  164. }
  165. JSON_CATCH(std::out_of_range&)
  166. {
  167. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  168. }
  169. // check if the string was completely read
  170. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  171. {
  172. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType()));
  173. }
  174. // only triggered on special platforms (like 32bit), see also
  175. // https://github.com/nlohmann/json/pull/2203
  176. if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)())) // NOLINT(runtime/int)
  177. {
  178. JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE
  179. }
  180. return static_cast<size_type>(res);
  181. }
  182. JSON_PRIVATE_UNLESS_TESTED:
  183. json_pointer top() const
  184. {
  185. if (JSON_HEDLEY_UNLIKELY(empty()))
  186. {
  187. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType()));
  188. }
  189. json_pointer result = *this;
  190. result.reference_tokens = {reference_tokens[0]};
  191. return result;
  192. }
  193. private:
  194. /*!
  195. @brief create and return a reference to the pointed to value
  196. @complexity Linear in the number of reference tokens.
  197. @throw parse_error.109 if array index is not a number
  198. @throw type_error.313 if value cannot be unflattened
  199. */
  200. BasicJsonType& get_and_create(BasicJsonType& j) const
  201. {
  202. auto* result = &j;
  203. // in case no reference tokens exist, return a reference to the JSON value
  204. // j which will be overwritten by a primitive value
  205. for (const auto& reference_token : reference_tokens)
  206. {
  207. switch (result->type())
  208. {
  209. case detail::value_t::null:
  210. {
  211. if (reference_token == "0")
  212. {
  213. // start a new array if reference token is 0
  214. result = &result->operator[](0);
  215. }
  216. else
  217. {
  218. // start a new object otherwise
  219. result = &result->operator[](reference_token);
  220. }
  221. break;
  222. }
  223. case detail::value_t::object:
  224. {
  225. // create an entry in the object
  226. result = &result->operator[](reference_token);
  227. break;
  228. }
  229. case detail::value_t::array:
  230. {
  231. // create an entry in the array
  232. result = &result->operator[](array_index(reference_token));
  233. break;
  234. }
  235. /*
  236. The following code is only reached if there exists a reference
  237. token _and_ the current value is primitive. In this case, we have
  238. an error situation, because primitive values may only occur as
  239. single value; that is, with an empty list of reference tokens.
  240. */
  241. case detail::value_t::string:
  242. case detail::value_t::boolean:
  243. case detail::value_t::number_integer:
  244. case detail::value_t::number_unsigned:
  245. case detail::value_t::number_float:
  246. case detail::value_t::binary:
  247. case detail::value_t::discarded:
  248. default:
  249. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j));
  250. }
  251. }
  252. return *result;
  253. }
  254. /*!
  255. @brief return a reference to the pointed to value
  256. @note This version does not throw if a value is not present, but tries to
  257. create nested values instead. For instance, calling this function
  258. with pointer `"/this/that"` on a null value is equivalent to calling
  259. `operator[]("this").operator[]("that")` on that value, effectively
  260. changing the null value to an object.
  261. @param[in] ptr a JSON value
  262. @return reference to the JSON value pointed to by the JSON pointer
  263. @complexity Linear in the length of the JSON pointer.
  264. @throw parse_error.106 if an array index begins with '0'
  265. @throw parse_error.109 if an array index was not a number
  266. @throw out_of_range.404 if the JSON pointer can not be resolved
  267. */
  268. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  269. {
  270. for (const auto& reference_token : reference_tokens)
  271. {
  272. // convert null values to arrays or objects before continuing
  273. if (ptr->is_null())
  274. {
  275. // check if reference token is a number
  276. const bool nums =
  277. std::all_of(reference_token.begin(), reference_token.end(),
  278. [](const unsigned char x)
  279. {
  280. return std::isdigit(x);
  281. });
  282. // change value to array for numbers or "-" or to object otherwise
  283. *ptr = (nums || reference_token == "-")
  284. ? detail::value_t::array
  285. : detail::value_t::object;
  286. }
  287. switch (ptr->type())
  288. {
  289. case detail::value_t::object:
  290. {
  291. // use unchecked object access
  292. ptr = &ptr->operator[](reference_token);
  293. break;
  294. }
  295. case detail::value_t::array:
  296. {
  297. if (reference_token == "-")
  298. {
  299. // explicitly treat "-" as index beyond the end
  300. ptr = &ptr->operator[](ptr->m_value.array->size());
  301. }
  302. else
  303. {
  304. // convert array index to number; unchecked access
  305. ptr = &ptr->operator[](array_index(reference_token));
  306. }
  307. break;
  308. }
  309. case detail::value_t::null:
  310. case detail::value_t::string:
  311. case detail::value_t::boolean:
  312. case detail::value_t::number_integer:
  313. case detail::value_t::number_unsigned:
  314. case detail::value_t::number_float:
  315. case detail::value_t::binary:
  316. case detail::value_t::discarded:
  317. default:
  318. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  319. }
  320. }
  321. return *ptr;
  322. }
  323. /*!
  324. @throw parse_error.106 if an array index begins with '0'
  325. @throw parse_error.109 if an array index was not a number
  326. @throw out_of_range.402 if the array index '-' is used
  327. @throw out_of_range.404 if the JSON pointer can not be resolved
  328. */
  329. BasicJsonType& get_checked(BasicJsonType* ptr) const
  330. {
  331. for (const auto& reference_token : reference_tokens)
  332. {
  333. switch (ptr->type())
  334. {
  335. case detail::value_t::object:
  336. {
  337. // note: at performs range check
  338. ptr = &ptr->at(reference_token);
  339. break;
  340. }
  341. case detail::value_t::array:
  342. {
  343. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  344. {
  345. // "-" always fails the range check
  346. JSON_THROW(detail::out_of_range::create(402,
  347. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  348. ") is out of range", *ptr));
  349. }
  350. // note: at performs range check
  351. ptr = &ptr->at(array_index(reference_token));
  352. break;
  353. }
  354. case detail::value_t::null:
  355. case detail::value_t::string:
  356. case detail::value_t::boolean:
  357. case detail::value_t::number_integer:
  358. case detail::value_t::number_unsigned:
  359. case detail::value_t::number_float:
  360. case detail::value_t::binary:
  361. case detail::value_t::discarded:
  362. default:
  363. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  364. }
  365. }
  366. return *ptr;
  367. }
  368. /*!
  369. @brief return a const reference to the pointed to value
  370. @param[in] ptr a JSON value
  371. @return const reference to the JSON value pointed to by the JSON
  372. pointer
  373. @throw parse_error.106 if an array index begins with '0'
  374. @throw parse_error.109 if an array index was not a number
  375. @throw out_of_range.402 if the array index '-' is used
  376. @throw out_of_range.404 if the JSON pointer can not be resolved
  377. */
  378. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  379. {
  380. for (const auto& reference_token : reference_tokens)
  381. {
  382. switch (ptr->type())
  383. {
  384. case detail::value_t::object:
  385. {
  386. // use unchecked object access
  387. ptr = &ptr->operator[](reference_token);
  388. break;
  389. }
  390. case detail::value_t::array:
  391. {
  392. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  393. {
  394. // "-" cannot be used for const access
  395. JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr));
  396. }
  397. // use unchecked array access
  398. ptr = &ptr->operator[](array_index(reference_token));
  399. break;
  400. }
  401. case detail::value_t::null:
  402. case detail::value_t::string:
  403. case detail::value_t::boolean:
  404. case detail::value_t::number_integer:
  405. case detail::value_t::number_unsigned:
  406. case detail::value_t::number_float:
  407. case detail::value_t::binary:
  408. case detail::value_t::discarded:
  409. default:
  410. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  411. }
  412. }
  413. return *ptr;
  414. }
  415. /*!
  416. @throw parse_error.106 if an array index begins with '0'
  417. @throw parse_error.109 if an array index was not a number
  418. @throw out_of_range.402 if the array index '-' is used
  419. @throw out_of_range.404 if the JSON pointer can not be resolved
  420. */
  421. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  422. {
  423. for (const auto& reference_token : reference_tokens)
  424. {
  425. switch (ptr->type())
  426. {
  427. case detail::value_t::object:
  428. {
  429. // note: at performs range check
  430. ptr = &ptr->at(reference_token);
  431. break;
  432. }
  433. case detail::value_t::array:
  434. {
  435. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  436. {
  437. // "-" always fails the range check
  438. JSON_THROW(detail::out_of_range::create(402,
  439. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  440. ") is out of range", *ptr));
  441. }
  442. // note: at performs range check
  443. ptr = &ptr->at(array_index(reference_token));
  444. break;
  445. }
  446. case detail::value_t::null:
  447. case detail::value_t::string:
  448. case detail::value_t::boolean:
  449. case detail::value_t::number_integer:
  450. case detail::value_t::number_unsigned:
  451. case detail::value_t::number_float:
  452. case detail::value_t::binary:
  453. case detail::value_t::discarded:
  454. default:
  455. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr));
  456. }
  457. }
  458. return *ptr;
  459. }
  460. /*!
  461. @throw parse_error.106 if an array index begins with '0'
  462. @throw parse_error.109 if an array index was not a number
  463. */
  464. bool contains(const BasicJsonType* ptr) const
  465. {
  466. for (const auto& reference_token : reference_tokens)
  467. {
  468. switch (ptr->type())
  469. {
  470. case detail::value_t::object:
  471. {
  472. if (!ptr->contains(reference_token))
  473. {
  474. // we did not find the key in the object
  475. return false;
  476. }
  477. ptr = &ptr->operator[](reference_token);
  478. break;
  479. }
  480. case detail::value_t::array:
  481. {
  482. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  483. {
  484. // "-" always fails the range check
  485. return false;
  486. }
  487. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
  488. {
  489. // invalid char
  490. return false;
  491. }
  492. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  493. {
  494. if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
  495. {
  496. // first char should be between '1' and '9'
  497. return false;
  498. }
  499. for (std::size_t i = 1; i < reference_token.size(); i++)
  500. {
  501. if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
  502. {
  503. // other char should be between '0' and '9'
  504. return false;
  505. }
  506. }
  507. }
  508. const auto idx = array_index(reference_token);
  509. if (idx >= ptr->size())
  510. {
  511. // index out of range
  512. return false;
  513. }
  514. ptr = &ptr->operator[](idx);
  515. break;
  516. }
  517. case detail::value_t::null:
  518. case detail::value_t::string:
  519. case detail::value_t::boolean:
  520. case detail::value_t::number_integer:
  521. case detail::value_t::number_unsigned:
  522. case detail::value_t::number_float:
  523. case detail::value_t::binary:
  524. case detail::value_t::discarded:
  525. default:
  526. {
  527. // we do not expect primitive values if there is still a
  528. // reference token to process
  529. return false;
  530. }
  531. }
  532. }
  533. // no reference token left means we found a primitive value
  534. return true;
  535. }
  536. /*!
  537. @brief split the string input to reference tokens
  538. @note This function is only called by the json_pointer constructor.
  539. All exceptions below are documented there.
  540. @throw parse_error.107 if the pointer is not empty or begins with '/'
  541. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  542. */
  543. static std::vector<std::string> split(const std::string& reference_string)
  544. {
  545. std::vector<std::string> result;
  546. // special case: empty reference string -> no reference tokens
  547. if (reference_string.empty())
  548. {
  549. return result;
  550. }
  551. // check if nonempty reference string begins with slash
  552. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  553. {
  554. JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType()));
  555. }
  556. // extract the reference tokens:
  557. // - slash: position of the last read slash (or end of string)
  558. // - start: position after the previous slash
  559. for (
  560. // search for the first slash after the first character
  561. std::size_t slash = reference_string.find_first_of('/', 1),
  562. // set the beginning of the first reference token
  563. start = 1;
  564. // we can stop if start == 0 (if slash == std::string::npos)
  565. start != 0;
  566. // set the beginning of the next reference token
  567. // (will eventually be 0 if slash == std::string::npos)
  568. start = (slash == std::string::npos) ? 0 : slash + 1,
  569. // find next slash
  570. slash = reference_string.find_first_of('/', start))
  571. {
  572. // use the text between the beginning of the reference token
  573. // (start) and the last slash (slash).
  574. auto reference_token = reference_string.substr(start, slash - start);
  575. // check reference tokens are properly escaped
  576. for (std::size_t pos = reference_token.find_first_of('~');
  577. pos != std::string::npos;
  578. pos = reference_token.find_first_of('~', pos + 1))
  579. {
  580. JSON_ASSERT(reference_token[pos] == '~');
  581. // ~ must be followed by 0 or 1
  582. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
  583. (reference_token[pos + 1] != '0' &&
  584. reference_token[pos + 1] != '1')))
  585. {
  586. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType()));
  587. }
  588. }
  589. // finally, store the reference token
  590. detail::unescape(reference_token);
  591. result.push_back(reference_token);
  592. }
  593. return result;
  594. }
  595. private:
  596. /*!
  597. @param[in] reference_string the reference string to the current value
  598. @param[in] value the value to consider
  599. @param[in,out] result the result object to insert values to
  600. @note Empty objects or arrays are flattened to `null`.
  601. */
  602. static void flatten(const std::string& reference_string,
  603. const BasicJsonType& value,
  604. BasicJsonType& result)
  605. {
  606. switch (value.type())
  607. {
  608. case detail::value_t::array:
  609. {
  610. if (value.m_value.array->empty())
  611. {
  612. // flatten empty array as null
  613. result[reference_string] = nullptr;
  614. }
  615. else
  616. {
  617. // iterate array and use index as reference string
  618. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  619. {
  620. flatten(reference_string + "/" + std::to_string(i),
  621. value.m_value.array->operator[](i), result);
  622. }
  623. }
  624. break;
  625. }
  626. case detail::value_t::object:
  627. {
  628. if (value.m_value.object->empty())
  629. {
  630. // flatten empty object as null
  631. result[reference_string] = nullptr;
  632. }
  633. else
  634. {
  635. // iterate object and use keys as reference string
  636. for (const auto& element : *value.m_value.object)
  637. {
  638. flatten(reference_string + "/" + detail::escape(element.first), element.second, result);
  639. }
  640. }
  641. break;
  642. }
  643. case detail::value_t::null:
  644. case detail::value_t::string:
  645. case detail::value_t::boolean:
  646. case detail::value_t::number_integer:
  647. case detail::value_t::number_unsigned:
  648. case detail::value_t::number_float:
  649. case detail::value_t::binary:
  650. case detail::value_t::discarded:
  651. default:
  652. {
  653. // add primitive value with its reference string
  654. result[reference_string] = value;
  655. break;
  656. }
  657. }
  658. }
  659. /*!
  660. @param[in] value flattened JSON
  661. @return unflattened JSON
  662. @throw parse_error.109 if array index is not a number
  663. @throw type_error.314 if value is not an object
  664. @throw type_error.315 if object values are not primitive
  665. @throw type_error.313 if value cannot be unflattened
  666. */
  667. static BasicJsonType
  668. unflatten(const BasicJsonType& value)
  669. {
  670. if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
  671. {
  672. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value));
  673. }
  674. BasicJsonType result;
  675. // iterate the JSON object values
  676. for (const auto& element : *value.m_value.object)
  677. {
  678. if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
  679. {
  680. JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second));
  681. }
  682. // assign value to reference pointed to by JSON pointer; Note that if
  683. // the JSON pointer is "" (i.e., points to the whole value), function
  684. // get_and_create returns a reference to result itself. An assignment
  685. // will then create a primitive value.
  686. json_pointer(element.first).get_and_create(result) = element.second;
  687. }
  688. return result;
  689. }
  690. /*!
  691. @brief compares two JSON pointers for equality
  692. @param[in] lhs JSON pointer to compare
  693. @param[in] rhs JSON pointer to compare
  694. @return whether @a lhs is equal to @a rhs
  695. @complexity Linear in the length of the JSON pointer
  696. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  697. */
  698. friend bool operator==(json_pointer const& lhs,
  699. json_pointer const& rhs) noexcept
  700. {
  701. return lhs.reference_tokens == rhs.reference_tokens;
  702. }
  703. /*!
  704. @brief compares two JSON pointers for inequality
  705. @param[in] lhs JSON pointer to compare
  706. @param[in] rhs JSON pointer to compare
  707. @return whether @a lhs is not equal @a rhs
  708. @complexity Linear in the length of the JSON pointer
  709. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  710. */
  711. friend bool operator!=(json_pointer const& lhs,
  712. json_pointer const& rhs) noexcept
  713. {
  714. return !(lhs == rhs);
  715. }
  716. /// the reference tokens
  717. std::vector<std::string> reference_tokens;
  718. };
  719. } // namespace nlohmann