json2xml master
C++ header-only json to xml converter
Loading...
Searching...
No Matches
json2xml.hpp
Go to the documentation of this file.
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
13Licensed under the MIT License <http://opensource.org/licenses/MIT>.
14SPDX-License-Identifier: MIT
15Copyright (c) 2020 Eduardo Ramos
16
17Permission is hereby granted, free of charge, to any person obtaining a copy
18of this software and associated documentation files (the "Software"), to deal
19in the Software without restriction, including without limitation the rights
20to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21copies of the Software, and to permit persons to whom the Software is
22furnished to do so, subject to the following conditions:
23
24The above copyright notice and this permission notice shall be included in all
25copies or substantial portions of the Software.
26
27THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33SOFTWARE.
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
50namespace ert {
51
84class 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 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 bool fail(const std::string& message) {
111 error_ = message;
112 result_.str("");
113 frames_.clear();
114 return false;
115 }
116
117 bool failNotObject() {
118 return fail("a json object is expected at top level");
119 }
120
121 std::string indentation(std::size_t depth) const {
122 return std::string(depth * tab_spaces_, ' ');
123 }
124
125 // Indentation level of the elements created within a frame
126 static std::size_t childDepth(const Frame& frame) {
127 switch (frame.type) {
128 case FrameType::Document:
129 return 0;
130 case FrameType::Element:
131 return frame.depth + 1;
132 default:
133 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 Frame& owner() {
139 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 std::string location() const {
144 std::string result;
145 for (const auto& frame : frames_) {
146 if (frame.type == FrameType::Element) result += "/" + frame.name;
147 }
148 const Frame& top = frames_.back();
149 if (top.type == FrameType::Array) {
150 result += "/" + top.name + "[]";
151 }
152 else {
153 result += "/" + (key_is_attribute_ ? std::string(1, attr_prefix_) : std::string()) + key_;
154 }
155 return result;
156 }
157
158 // Name and indentation of the element created by the current value (keyed or array item)
159 std::pair<std::string, std::size_t> newElement() const {
160 const Frame& top = frames_.back();
161 return {top.type == FrameType::Array ? top.name : key_, childDepth(top)};
162 }
163
164 void appendElement(Frame& target, const std::string& name, std::size_t depth,
165 const std::string& attributes, const std::string& children) {
166 target.children += indentation(depth) + "<" + name + attributes;
167 if (children.empty()) {
168 target.children += "/>\n";
169 }
170 else {
171 target.children += ">\n" + children + indentation(depth) + "</" + name + ">\n";
172 }
173 }
174
175 static bool isNameStartChar(unsigned char c) {
176 // ASCII letters, '_', ':' and any non-ASCII (UTF-8) byte
177 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':' || c >= 0x80;
178 }
179
180 static bool isNameChar(unsigned char c) {
181 return isNameStartChar(c) || (c >= '0' && c <= '9') || c == '-' || c == '.';
182 }
183
184 static bool isValidName(const std::string& name) {
185 if (name.empty() || !isNameStartChar(static_cast<unsigned char>(name[0]))) return false;
186 for (char c : name) {
187 if (!isNameChar(static_cast<unsigned char>(c))) return false;
188 }
189 return true;
190 }
191
192 // Escapes an attribute value; false for characters not allowed in XML 1.0
193 static bool escape(const std::string& value, std::string& out) {
194 for (char ch : value) {
195 const unsigned char c = static_cast<unsigned char>(ch);
196 switch (c) {
197 case '&':
198 out += "&amp;";
199 break;
200 case '<':
201 out += "&lt;";
202 break;
203 case '>':
204 out += "&gt;";
205 break;
206 case '"':
207 out += "&quot;";
208 break;
209 case '\t':
210 out += "&#9;";
211 break;
212 case '\n':
213 out += "&#10;";
214 break;
215 case '\r':
216 out += "&#13;";
217 break;
218 default:
219 if (c < 0x20) return false;
220 out += ch;
221 }
222 }
223 return true;
224 }
225
226 // String, number and boolean values: only valid as attribute values
227 bool scalar(const std::string& value, const std::string& type) {
228 if (frames_.empty()) return failNotObject();
229 Frame& top = frames_.back();
230 if (top.type == FrameType::Array || !key_is_attribute_) {
231 return fail(type + " value at '" + location() + "': text content is not supported (only attributes have scalar values)");
232 }
233 std::string escaped;
234 if (!escape(value, escaped)) {
235 return fail("value of attribute '" + location() + "' has a character not allowed in XML");
236 }
237 if (!top.attributeNames.insert(key_).second) {
238 return fail("repeated attribute '" + location() + "'");
239 }
240 top.attributes += " " + key_ + "=\"" + escaped + "\"";
241 return true;
242 }
243
244 bool failAttributeType(const std::string& type) {
245 return fail(type + " value for attribute '" + location() + "': must be a string, number or boolean");
246 }
247
248public:
249
256 JsonSaxConsumer(int tabSpaces = 4, char attrPrefix = '@'):
257 tab_spaces_(tabSpaces >= 1 ? tabSpaces : 4),
258 attr_prefix_(attrPrefix) {}
259
263 const std::stringstream & getXmlStream() const {
264 return result_;
265 }
266
270 std::string getXmlString() const {
271 return result_.str();
272 }
273
277 const std::string & getError() const {
278 return error_;
279 }
280
281 // nlohmann sax virtual methods
282 bool null() override
283 {
284 if (frames_.empty()) return failNotObject();
285 if (frames_.back().type != FrameType::Array && key_is_attribute_) return failAttributeType("null");
286 const auto element = newElement();
287 appendElement(owner(), element.first, element.second, "", ""); // empty element
288 return true;
289 }
290
291 bool boolean(bool val) override
292 {
293 return scalar(val ? "true" : "false", "boolean");
294 }
295
296 bool number_integer(number_integer_t val) override
297 {
298 return scalar(std::to_string(val), "number");
299 }
300
301 bool number_unsigned(number_unsigned_t val) override
302 {
303 return scalar(std::to_string(val), "number");
304 }
305
306 bool number_float(number_float_t /*val*/, const string_t& s) override
307 {
308 return scalar(s, "number"); // as written in the json document
309 }
310
311 bool string(string_t& val) override
312 {
313 return scalar(val, "string");
314 }
315
316 bool binary(binary_t& /*val*/) override
317 {
318 if (frames_.empty()) return failNotObject();
319 return fail("binary value at '" + location() + "' is not supported");
320 }
321
322 bool start_object(std::size_t /*elements*/) override
323 {
324 if (frames_.empty()) { // document start: a new conversion
325 result_.str("");
326 error_.clear();
327 frames_.emplace_back(FrameType::Document, "", 0);
328 return true;
329 }
330 if (frames_.back().type != FrameType::Array && key_is_attribute_) return failAttributeType("object");
331 auto element = newElement();
332 frames_.emplace_back(FrameType::Element, std::move(element.first), element.second);
333 return true;
334 }
335
336 bool end_object() override
337 {
338 Frame frame = std::move(frames_.back());
339 frames_.pop_back();
340
341 if (frame.type == FrameType::Document) {
342 if (frame.children.empty()) return fail("the json object has no element");
343 frame.children.pop_back(); // no trailing new line
344 result_ << frame.children;
345 return true;
346 }
347
348 appendElement(owner(), frame.name, frame.depth, frame.attributes, frame.children);
349 return true;
350 }
351
352 bool start_array(std::size_t /*elements*/) override
353 {
354 if (frames_.empty()) return failNotObject();
355 if (frames_.back().type == FrameType::Array) {
356 return fail("nested array at '" + location() + "' is not supported");
357 }
358 if (key_is_attribute_) return failAttributeType("array");
359 auto element = newElement();
360 frames_.emplace_back(FrameType::Array, std::move(element.first), element.second);
361 return true;
362 }
363
364 bool end_array() override
365 {
366 frames_.pop_back();
367 return true;
368 }
369
370 bool key(string_t& val) override
371 {
372 const bool attribute = !val.empty() && val[0] == attr_prefix_;
373 key_ = attribute ? val.substr(1) : val;
374 key_is_attribute_ = attribute;
375
376 if (!isValidName(key_)) {
377 return fail(std::string(attribute ? "attribute" : "element") + " name '" + val + "' at '" + location() + "' is not a valid XML name");
378 }
379 if (attribute && frames_.back().type == FrameType::Document) {
380 return fail("attribute '" + val + "' at top level: attributes belong to an element");
381 }
382 return true;
383 }
384
385 bool parse_error(std::size_t /*position*/, const std::string& /*last_token*/, const nlohmann::json::exception& ex) override
386 {
387 return fail(ex.what());
388 }
389};
390
391}
392
393#endif
const std::stringstream & getXmlStream() const
Definition json2xml.hpp:263
bool boolean(bool val) override
Definition json2xml.hpp:291
bool start_array(std::size_t) override
Definition json2xml.hpp:352
bool end_array() override
Definition json2xml.hpp:364
bool key(string_t &val) override
Definition json2xml.hpp:370
bool string(string_t &val) override
Definition json2xml.hpp:311
bool number_unsigned(number_unsigned_t val) override
Definition json2xml.hpp:301
bool null() override
Definition json2xml.hpp:282
bool binary(binary_t &) override
Definition json2xml.hpp:316
bool end_object() override
Definition json2xml.hpp:336
const std::string & getError() const
Definition json2xml.hpp:277
bool start_object(std::size_t) override
Definition json2xml.hpp:322
JsonSaxConsumer(int tabSpaces=4, char attrPrefix='@')
Definition json2xml.hpp:256
bool number_float(number_float_t, const string_t &s) override
Definition json2xml.hpp:306
std::string getXmlString() const
Definition json2xml.hpp:270
bool parse_error(std::size_t, const std::string &, const nlohmann::json::exception &ex) override
Definition json2xml.hpp:385
bool number_integer(number_integer_t val) override
Definition json2xml.hpp:296