LCOV - code coverage report
Current view: top level - ert - json2xml.hpp (source / functions) Coverage Total Hit
Test: coverage.info Lines: 97.6 % 166 162
Test Date: 2026-11-16 19:12:59 Functions: 96.9 % 32 31

            Line data    Source code
       1              : /*
       2              :  ________________________________________________
       3              : |     _                 ___                 _   |
       4              : |    (_)               |__ \               | |  |
       5              : |     _ ___  ___  _ __    ) |_  ___ __ ___ | |  |
       6              : |    | / __|/ _ \| '_ \  / /\ \/ / '_ ` _ \| |  |  Json-to-xml C++ only-header library
       7              : |    | \__ \ (_) | | | |/ /_ >  <| | | | | | |  |  Version 1.1.0
       8              : |    | |___/\___/|_| |_|____/_/\_\_| |_| |_|_|  |  https://github.com/testillano/json2xml
       9              : |   _/ |                                        |
      10              : |  |__/                                         |
      11              : |_______________________________________________|
      12              : 
      13              : Licensed under the MIT License <http://opensource.org/licenses/MIT>.
      14              : SPDX-License-Identifier: MIT
      15              : Copyright (c) 2020 Eduardo Ramos
      16              : 
      17              : Permission is hereby  granted, free of charge, to any  person obtaining a copy
      18              : of this software and associated  documentation files (the "Software"), to deal
      19              : in the Software  without restriction, including without  limitation the rights
      20              : to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
      21              : copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
      22              : furnished to do so, subject to the following conditions:
      23              : 
      24              : The above copyright notice and this permission notice shall be included in all
      25              : copies or substantial portions of the Software.
      26              : 
      27              : THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
      28              : IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
      29              : FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
      30              : AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
      31              : LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      32              : OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
      33              : SOFTWARE.
      34              : */
      35              : 
      36              : #ifndef ERT_JSONSAXCONSUMER_H_
      37              : #define ERT_JSONSAXCONSUMER_H_
      38              : 
      39              : // Standard
      40              : #include <cstddef>
      41              : #include <set>
      42              : #include <sstream>
      43              : #include <string>
      44              : #include <utility>
      45              : #include <vector>
      46              : 
      47              : // Nlohmann (https://github.com/nlohmann/json)
      48              : #include <nlohmann/json.hpp>
      49              : 
      50              : namespace ert {
      51              : 
      52              : /**
      53              :  * Json SAX consumer building the XML representation of the parsed json document.
      54              :  *
      55              :  * The json layout is the one of python xmltodict, restricted to elements and
      56              :  * attributes:
      57              :  *
      58              :  * - The top level json value must be an object: each of its keys is a root
      59              :  *   element (normally one; several give an XML fragment).
      60              :  * - A key with an object value is an element: its prefixed keys ('@' by default)
      61              :  *   with scalar values (string, number, boolean) are the attributes, and the
      62              :  *   other keys the child elements. Attributes are written first, wherever they
      63              :  *   are in the object.
      64              :  * - A key with an array value is a repeated element: one per item (objects, or
      65              :  *   nulls for empty elements).
      66              :  * - A key with a null value, or an empty object, is an empty element.
      67              :  *
      68              :  * The conversion fails (sax_parse() returns false and getError() tells why) on
      69              :  * json parse errors and on what is not supported: text content (an element key
      70              :  * with a scalar value, or an array of scalars), nested arrays, attributes at top
      71              :  * level, with object/array/null values or repeated, invalid XML names, and
      72              :  * characters not allowed in XML 1.0. Attribute values are escaped ('&', '<',
      73              :  * '>', '"', tab, line feed and carriage return).
      74              :  *
      75              :  * Usage:
      76              :  * @code
      77              :  * ert::JsonSaxConsumer consumer(2);
      78              :  * if (nlohmann::json::sax_parse(jsonString, &consumer)) xml = consumer.getXmlString();
      79              :  * else error = consumer.getError();
      80              :  * @endcode
      81              :  *
      82              :  * A consumer can be reused: every parse starts from scratch.
      83              :  */
      84              : class JsonSaxConsumer : public nlohmann::json::json_sax_t
      85              : {
      86              :     enum class FrameType { Document, Element, Array };
      87              : 
      88              :     // Open json container
      89              :     struct Frame {
      90              :         FrameType type;
      91              :         std::string name;                    // element name (Element), repeated element name (Array)
      92              :         std::size_t depth;                   // indentation level of the element(s) (Element, Array)
      93              :         std::string attributes;              // ' name="value"' list (Element)
      94              :         std::set<std::string> attributeNames; // to reject repeated attributes (Element)
      95              :         std::string children;                // rendered child elements (Document, Element)
      96              : 
      97          239 :         Frame(FrameType t, std::string n, std::size_t d) : type(t), name(std::move(n)), depth(d) {}
      98              :     };
      99              : 
     100              :     // private members
     101              :     int tab_spaces_;
     102              :     char attr_prefix_;
     103              :     std::stringstream result_;
     104              :     std::string error_;
     105              :     std::vector<Frame> frames_;
     106              :     std::string key_;              // last key: element name, or attribute name without prefix
     107              :     bool key_is_attribute_ = false;
     108              : 
     109              :     // private functions
     110           41 :     bool fail(const std::string& message) {
     111           41 :         error_ = message;
     112           82 :         result_.str("");
     113           41 :         frames_.clear();
     114           41 :         return false;
     115              :     }
     116              : 
     117            5 :     bool failNotObject() {
     118           10 :         return fail("a json object is expected at top level");
     119              :     }
     120              : 
     121          170 :     std::string indentation(std::size_t depth) const {
     122          340 :         return std::string(depth * tab_spaces_, ' ');
     123              :     }
     124              : 
     125              :     // Indentation level of the elements created within a frame
     126          163 :     static std::size_t childDepth(const Frame& frame) {
     127          163 :         switch (frame.type) {
     128           72 :         case FrameType::Document:
     129           72 :             return 0;
     130           58 :         case FrameType::Element:
     131           58 :             return frame.depth + 1;
     132           33 :         default:
     133           33 :             return frame.depth; // array items
     134              :         }
     135              :     }
     136              : 
     137              :     // Frame where the elements created now are rendered (array items go to the array owner)
     138          124 :     Frame& owner() {
     139          124 :         return frames_.back().type == FrameType::Array ? frames_[frames_.size() - 2] : frames_.back();
     140              :     }
     141              : 
     142              :     // Json location of the current value, for error messages (e.g. '/a/b/@c')
     143           29 :     std::string location() const {
     144           29 :         std::string result;
     145           79 :         for (const auto& frame : frames_) {
     146           50 :             if (frame.type == FrameType::Element) result += "/" + frame.name;
     147              :         }
     148           29 :         const Frame& top = frames_.back();
     149           29 :         if (top.type == FrameType::Array) {
     150            5 :             result += "/" + top.name + "[]";
     151              :         }
     152              :         else {
     153           42 :             result += "/" + (key_is_attribute_ ? std::string(1, attr_prefix_) : std::string()) + key_;
     154              :         }
     155           29 :         return result;
     156            0 :     }
     157              : 
     158              :     // Name and indentation of the element created by the current value (keyed or array item)
     159          163 :     std::pair<std::string, std::size_t> newElement() const {
     160          163 :         const Frame& top = frames_.back();
     161          326 :         return {top.type == FrameType::Array ? top.name : key_, childDepth(top)};
     162              :     }
     163              : 
     164          124 :     void appendElement(Frame& target, const std::string& name, std::size_t depth,
     165              :                        const std::string& attributes, const std::string& children) {
     166          124 :         target.children += indentation(depth) + "<" + name + attributes;
     167          124 :         if (children.empty()) {
     168           78 :             target.children += "/>\n";
     169              :         }
     170              :         else {
     171           46 :             target.children += ">\n" + children + indentation(depth) + "</" + name + ">\n";
     172              :         }
     173          124 :     }
     174              : 
     175          838 :     static bool isNameStartChar(unsigned char c) {
     176              :         // ASCII letters, '_', ':' and any non-ASCII (UTF-8) byte
     177          838 :         return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':' || c >= 0x80;
     178              :     }
     179              : 
     180          593 :     static bool isNameChar(unsigned char c) {
     181          593 :         return isNameStartChar(c) || (c >= '0' && c <= '9') || c == '-' || c == '.';
     182              :     }
     183              : 
     184          248 :     static bool isValidName(const std::string& name) {
     185          248 :         if (name.empty() || !isNameStartChar(static_cast<unsigned char>(name[0]))) return false;
     186          830 :         for (char c : name) {
     187          593 :             if (!isNameChar(static_cast<unsigned char>(c))) return false;
     188              :         }
     189          237 :         return true;
     190              :     }
     191              : 
     192              :     // Escapes an attribute value; false for characters not allowed in XML 1.0
     193           92 :     static bool escape(const std::string& value, std::string& out) {
     194          477 :         for (char ch : value) {
     195          386 :             const unsigned char c = static_cast<unsigned char>(ch);
     196          386 :             switch (c) {
     197            2 :             case '&':
     198            2 :                 out += "&amp;";
     199            2 :                 break;
     200            2 :             case '<':
     201            2 :                 out += "&lt;";
     202            2 :                 break;
     203            2 :             case '>':
     204            2 :                 out += "&gt;";
     205            2 :                 break;
     206            2 :             case '"':
     207            2 :                 out += "&quot;";
     208            2 :                 break;
     209            2 :             case '\t':
     210            2 :                 out += "&#9;";
     211            2 :                 break;
     212            2 :             case '\n':
     213            2 :                 out += "&#10;";
     214            2 :                 break;
     215            2 :             case '\r':
     216            2 :                 out += "&#13;";
     217            2 :                 break;
     218          372 :             default:
     219          372 :                 if (c < 0x20) return false;
     220          371 :                 out += ch;
     221              :             }
     222              :         }
     223           91 :         return true;
     224              :     }
     225              : 
     226              :     // String, number and boolean values: only valid as attribute values
     227          104 :     bool scalar(const std::string& value, const std::string& type) {
     228          104 :         if (frames_.empty()) return failNotObject();
     229          102 :         Frame& top = frames_.back();
     230          102 :         if (top.type == FrameType::Array || !key_is_attribute_) {
     231           10 :             return fail(type + " value at '" + location() + "': text content is not supported (only attributes have scalar values)");
     232              :         }
     233           92 :         std::string escaped;
     234           92 :         if (!escape(value, escaped)) {
     235            1 :             return fail("value of attribute '" + location() + "' has a character not allowed in XML");
     236              :         }
     237           91 :         if (!top.attributeNames.insert(key_).second) {
     238            1 :             return fail("repeated attribute '" + location() + "'");
     239              :         }
     240           90 :         top.attributes += " " + key_ + "=\"" + escaped + "\"";
     241           90 :         return true;
     242           92 :     }
     243              : 
     244            4 :     bool failAttributeType(const std::string& type) {
     245            4 :         return fail(type + " value for attribute '" + location() + "': must be a string, number or boolean");
     246              :     }
     247              : 
     248              : public:
     249              : 
     250              :     /**
     251              :     * Default constructor
     252              :     *
     253              :     * @param tabSpaces Indentation spaces for xml representation, 4 by default. Must be >= 1 or 4 will be asigned.
     254              :     * @param attrPrefix You could set any other value for attribute prefix, '@' by default.
     255              :     */
     256           89 :     JsonSaxConsumer(int tabSpaces = 4, char attrPrefix = '@'):
     257           89 :         tab_spaces_(tabSpaces >= 1 ? tabSpaces : 4),
     258          178 :         attr_prefix_(attrPrefix) {}
     259              : 
     260              :     /**
     261              :     * Returns the resulting xml stringstream representation (empty on failure)
     262              :     */
     263            1 :     const std::stringstream & getXmlStream() const {
     264            1 :         return result_;
     265              :     }
     266              : 
     267              :     /**
     268              :     * Returns the resulting xml string representation (empty on failure)
     269              :     */
     270           84 :     std::string getXmlString() const {
     271           84 :         return result_.str();
     272              :     }
     273              : 
     274              :     /**
     275              :     * Returns the reason of the last failed conversion (empty on success)
     276              :     */
     277           78 :     const std::string & getError() const {
     278           78 :         return error_;
     279              :     }
     280              : 
     281              :     // nlohmann sax virtual methods
     282           13 :     bool null() override
     283              :     {
     284           13 :         if (frames_.empty()) return failNotObject();
     285           16 :         if (frames_.back().type != FrameType::Array && key_is_attribute_) return failAttributeType("null");
     286           10 :         const auto element = newElement();
     287           30 :         appendElement(owner(), element.first, element.second, "", ""); // empty element
     288           10 :         return true;
     289           10 :     }
     290              : 
     291            3 :     bool boolean(bool val) override
     292              :     {
     293           12 :         return scalar(val ? "true" : "false", "boolean");
     294              :     }
     295              : 
     296            1 :     bool number_integer(number_integer_t val) override
     297              :     {
     298            2 :         return scalar(std::to_string(val), "number");
     299              :     }
     300              : 
     301            3 :     bool number_unsigned(number_unsigned_t val) override
     302              :     {
     303            6 :         return scalar(std::to_string(val), "number");
     304              :     }
     305              : 
     306            2 :     bool number_float(number_float_t /*val*/, const string_t& s) override
     307              :     {
     308            4 :         return scalar(s, "number"); // as written in the json document
     309              :     }
     310              : 
     311           95 :     bool string(string_t& val) override
     312              :     {
     313          190 :         return scalar(val, "string");
     314              :     }
     315              : 
     316            0 :     bool binary(binary_t& /*val*/) override
     317              :     {
     318            0 :         if (frames_.empty()) return failNotObject();
     319            0 :         return fail("binary value at '" + location() + "' is not supported");
     320              :     }
     321              : 
     322          217 :     bool start_object(std::size_t /*elements*/) override
     323              :     {
     324          217 :         if (frames_.empty()) { // document start: a new conversion
     325          172 :             result_.str("");
     326           86 :             error_.clear();
     327           86 :             frames_.emplace_back(FrameType::Document, "", 0);
     328           86 :             return true;
     329              :         }
     330          133 :         if (frames_.back().type != FrameType::Array && key_is_attribute_) return failAttributeType("object");
     331          130 :         auto element = newElement();
     332          130 :         frames_.emplace_back(FrameType::Element, std::move(element.first), element.second);
     333          130 :         return true;
     334          130 :     }
     335              : 
     336          167 :     bool end_object() override
     337              :     {
     338          167 :         Frame frame = std::move(frames_.back());
     339          167 :         frames_.pop_back();
     340              : 
     341          167 :         if (frame.type == FrameType::Document) {
     342           55 :             if (frame.children.empty()) return fail("the json object has no element");
     343           52 :             frame.children.pop_back(); // no trailing new line
     344           52 :             result_ << frame.children;
     345           52 :             return true;
     346              :         }
     347              : 
     348          114 :         appendElement(owner(), frame.name, frame.depth, frame.attributes, frame.children);
     349          114 :         return true;
     350          167 :     }
     351              : 
     352           28 :     bool start_array(std::size_t /*elements*/) override
     353              :     {
     354           28 :         if (frames_.empty()) return failNotObject();
     355           26 :         if (frames_.back().type == FrameType::Array) {
     356            2 :             return fail("nested array at '" + location() + "' is not supported");
     357              :         }
     358           26 :         if (key_is_attribute_) return failAttributeType("array");
     359           23 :         auto element = newElement();
     360           23 :         frames_.emplace_back(FrameType::Array, std::move(element.first), element.second);
     361           23 :         return true;
     362           23 :     }
     363              : 
     364           18 :     bool end_array() override
     365              :     {
     366           18 :         frames_.pop_back();
     367           18 :         return true;
     368              :     }
     369              : 
     370          248 :     bool key(string_t& val) override
     371              :     {
     372          248 :         const bool attribute = !val.empty() && val[0] == attr_prefix_;
     373          248 :         key_ = attribute ? val.substr(1) : val;
     374          248 :         key_is_attribute_ = attribute;
     375              : 
     376          248 :         if (!isValidName(key_)) {
     377           33 :             return fail(std::string(attribute ? "attribute" : "element") + " name '" + val + "' at '" + location() + "' is not a valid XML name");
     378              :         }
     379          237 :         if (attribute && frames_.back().type == FrameType::Document) {
     380            2 :             return fail("attribute '" + val + "' at top level: attributes belong to an element");
     381              :         }
     382          235 :         return true;
     383              :     }
     384              : 
     385            4 :     bool parse_error(std::size_t /*position*/, const std::string& /*last_token*/, const nlohmann::json::exception& ex) override
     386              :     {
     387            8 :         return fail(ex.what());
     388              :     }
     389              : };
     390              : 
     391              : }
     392              : 
     393              : #endif
        

Generated by: LCOV version 2.0-1