From 9aff332bc8f39874ee2c538b3bf85c58d3bf5461 Mon Sep 17 00:00:00 2001 From: Sfinktah Bungholio Date: Thu, 30 Nov 2017 15:30:26 +1100 Subject: [PATCH 1/2] simple .each/.forEach extension --- src/json.hpp | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/json.hpp b/src/json.hpp index 9754e464c..f01e427a4 100644 --- a/src/json.hpp +++ b/src/json.hpp @@ -13658,6 +13658,59 @@ class basic_json return ptr.get_checked(this); } + /*! + @brief execute a provided function once for each item in a container + + Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining. + + @param iteratee Callable object accepting 3 arguments + @param iteratee.value The value of the current item + @param iteratee.key The key/index of the current item + @param iteratee.object The JSON container being iterated + + @throw type_error.302 if not is_object() or not is_array() + + @complexity Linear in the size the JSON container. + + @example j["list"].each([](auto key, auto value, auto& object){ object[key] = std::to_string(value); }); + + @since never + */ + template + void each(Function function) + { + basic_json& value = *this; + switch (value.m_type) + { + case detail::value_t::array: + { + // iterate array and use index as reference string + for (std::size_t i = 0; i < value.m_value.array->size(); ++i) + { + function(value.m_value.array->operator[](i), i, value); + } + } + break; + + case detail::value_t::object: + { + // iterate object and use keys as reference string + for (const auto& element : *value.m_value.object) + { + function(element.second, element.first, value); + } + break; + } + + default: + { + // maybe throw an error + JSON_THROW(type_error::create(302, "type must be array or object, but is " + std::string(value.type_name()))); + break; + } + } + } + /*! @brief return flattened JSON value From 5e984a2445748e62a3d024107da5eca574b07906 Mon Sep 17 00:00:00 2001 From: Sfinktah Bungholio Date: Tue, 5 Dec 2017 00:01:24 +1100 Subject: [PATCH 2/2] To lead people, you must follow behind. --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 62778419b..d6395fc51 100644 --- a/.travis.yml +++ b/.travis.yml @@ -279,3 +279,4 @@ script: brew install nlohmann_json --HEAD ; brew test nlohmann_json ; fi +