Loading...
Searching...
No Matches
JSON.h
1/*
2
3MIT License
4
5Copyright (c) 2017 FMI Open Development / Markus Peura, first.last@fmi.fi
6
7Permission is hereby granted, free of charge, to any person obtaining a copy
8of this software and associated documentation files (the "Software"), to deal
9in the Software without restriction, including without limitation the rights
10to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11copies of the Software, and to permit persons to whom the Software is
12furnished to do so, subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24
25*/
26/*
27Part of Rack development has been done in the BALTRAD projects part-financed
28by the European Union (European Regional Development Fund and European
29Neighbourhood Partnership Instrument, Baltic Sea Region Programme 2007-2013)
30*/
31#ifndef DRAIN_JSON
32#define DRAIN_JSON
33
34#include <string>
35
36//#include <drain/Reference.h> // experimental link tree.member ?
37#include <drain/Sprinter.h>
38
39#include "FileInfo.h"
40#include "TextReader.h"
41#include "TreeUnordered.h"
42
43
44namespace drain
45{
46
48/*'
49 * Applicable in reading configuration files and comments containing:
50 * -# plain numbers, distinguishing integers and floats
51 * -# arrays of numbers, surrounded by braces [,]
52 * -# strings, surrounded by double hyphens (")
53 *
54 * Applies TextReader::scanSegment in reading character streams.
55 * Uses Type::guessArrayType() for deriving compatible storage type for arrays.
56 *
57 * For writing, the new Sprinter::toStream is preferred to JSONwriter, which is deprecating.
58 *
59 */
60class JSON {
61
62public:
63
64
65 static FileInfo fileInfo;
66
68
71 template <class T>
72 static
73 void readTree(T & tree, std::istream & istr);
74
76
79 template <class T>
80 static
81 std::ostream & treeToStream(std::ostream & ostr, const T & tree, const drain::SprinterLayout & layout = drain::Sprinter::jsonLayout, short indent=0);
82
83
85 static
86 void readValue(std::istream & istr, Castable & v, bool keepType = false);
87 //void readValue(std::istream & istr, Variable & v, bool keepType = false);
88
90
96 static
97 void readValue(const std::string & s, Castable & v, bool keepType = false);
98 //void readValue(const std::string & s, Variable & v, bool keepType = false);
99
101 static
102 void readArray(const std::string & s, Castable & v);
103 //void readArray(const std::string & s, Variable & v);
104
105protected:
106
108 template <class T>
109 static
110 void handleValue(std::istream & istr, T & tree, const std::string & key){ // tree + key VariableMap! (as long as Palette (or others) use JSONtree with that)
111 drain::Logger log(__FILE__, __FUNCTION__);
112 log.unimplemented("type:", typeid(T).name());
113 log.error("stop..");
114 }
115 // To be later replaced with:
116 // void handleValue(std::istream & istr, T & child);
117
118
119};
120
121template <class T>
122std::ostream & JSON::treeToStream(std::ostream & ostr, const T & tree, const drain::SprinterLayout & layout, short indent){
123
124 const bool DATA = !tree.data.empty();
125 // const bool CHILDREN = !tree.empty(); // Check: is this potentially overridden to (children.empty() && data.empty())
126 const bool CHILDREN = tree.hasChildren(); // Check: is this potentially overridden to (children.empty() && data.empty())
127
128 /*
129 if (! (DATA||CHILDREN)){
130 // Also empty element should return something, here {}, but could be "" or null ?
131 ostr << layout.mapChars.prefix << layout.mapChars.suffix; // '\n';
132 return ostr;
133 }
134 */
135
136 if (! (DATA||CHILDREN)){
137 // Also empty element should return something, here {}, but could be "" or null ?
138 // ostr << layout.mapChars.prefix << ' ' << layout.mapChars.suffix; // '\n'; // remove debug-space
139 if (!DATA){
140 ostr << layout.mapChars.prefix << " " << layout.mapChars.suffix;
141 }
142 else {
143 ostr << layout.mapChars.prefix << ' ' << layout.mapChars.suffix;
144 }
145 return ostr;
146 }
147
148
149 const std::string pad(2*indent, ' ');
150
151 if (DATA){
152 drain::Sprinter::toStream(ostr, tree.data, layout);
153 //ostr << layout.pairChars.suffix;
154 return ostr; // = pratically exclusive
155 /*
156 if (CHILDREN)
157 ostr << layout.mapChars.separator;
158 ostr << '\n';
159 */
160 }
161
162 ostr << layout.mapChars.prefix; // << '\n';
163 //ostr << layout.pairChars.prefix;
164 ostr << '\n';
165
166 if (CHILDREN){
167 char sep = 0;
168 for (const auto & entry: tree){
169 if (sep){
170 ostr << sep;
171 ostr << '\n';
172 }
173 else {
174 sep = layout.mapChars.separator;
175 }
176 //ostr << pad << " " << '"' << entry.first << '"' << layout.pairChars.separator << ' '; // if empty?
177 ostr << pad << " "; // if empty?
178 // if (layout.pairChars.prefix)
179 ostr << layout.pairChars.prefix;
180 ostr << '"' << entry.first << '"' << layout.pairChars.separator << ' '; // if empty?
181 treeToStream(ostr, entry.second, layout, indent+1); // recursion
182 // if (layout.pairChars.suffix)
183 ostr << layout.pairChars.suffix;
184 }
185 ostr << '\n';
186 }
187
188 // if (layout.mapChars.suffix)
189 ostr << pad << layout.mapChars.suffix; // << '\n';
190
191 return ostr;
192}
193
194template <class T>
195void JSON::readTree(T & tree, std::istream & istr){
196
197 drain::Logger log(__FILE__, __FUNCTION__);
198
199
200 if (!istr){
201 log.error("File read error");
202 return;
203 }
204
205 char c;
206
208 c = istr.get();
209 if (c != '{'){
210 log.error("Syntax error: read '", c, "' when expecting '{'");
211 return;
212 }
213
214 std::string key;
215 std::string value;
216
217 // Debugging. Incomplete segments raise warnings.
218 bool completed = true; //
219
220 while (istr){
221
223
224 if (!istr)
225 return;
226
227 c = istr.get();
228
229 if (c == '"'){ // New key, starting new entry
230
231 key = TextReader::scanSegment(istr, "\"");
232 istr.get(); // swallow '"'
234 c = istr.get();
235 // log.warn() << " then4: " << (char)istr.peek() << log.endl;
236
237 if (c == ':'){
238 //handleValue(istr, tree, key);
239
240 handleValue(istr, tree, key);
241 // log.note(" - end: ", key);
242 completed = true;
243 }
244 else {
245 log.error() << "Syntax error: read \"" << key << "\" followed by '" << c << "' when expecting object {...}, string \"...\", array [...], or number" << log.endl;
246 return;
247 }
248 }
249 else if (c == '}'){
250 if (!completed) // comma encountered after empty segment
251 log.warn("empty section after key=", key);
252 //log.warn("closing '}' for ", key);
253 return;
254 }
255 else if (c == ','){
256 //if (!completed) // comma encountered after empty segment
257 // log.warn("empty section after key=", key);
258 completed = false; // trap for subsequent check
259 }
260 else { // TODO: warn if comma encountered after empty
261 log.error("Syntax error: char '", c, "' (", (short)c, "), expected '\"', '}' or ','");
262 return;
263 }
264
265 }
266
267}
268
269
270// New 2023 "implementation"
271typedef drain::UnorderedMultiTree<drain::Variable,true> JSONtree;
272
273// Todo -> .cpp
274template <>
275inline
276void drain::JSON::handleValue(std::istream & istr, JSONtree & dst, const std::string & key){
277//void drain::JSON::handleValue(std::istream & istr, JSONtree & child){
278
279 drain::Logger log( __FILE__, __FUNCTION__);
280
281
282 //JSONtree & child = dst.addChild(key);
283 JSONtree & child = dst[key];
284
286
287 char c = istr.peek();
288
289 if (c == '{'){
290 // log.warn("Reading object '", key, "'");
291 JSON::readTree(child, istr);
292 }
293 else {
294 // log.warn("Reading value '", key, "'");
295 JSON::readValue(istr, child.data);
296 }
297
298 return;
299}
300
301
302template <>
303std::ostream & JSON::treeToStream(std::ostream & ostr, const JSONtree & tree, const drain::SprinterLayout & layout, short indent);
304
305template <>
306inline
307std::ostream & drain::Sprinter::toStream(std::ostream & ostr, const JSONtree & tree, const drain::SprinterLayout & layout){
308 return drain::JSON::treeToStream(ostr, tree, layout);
309 //return drain::Sprinter::treeToStream(ostr, tree, layout);
310}
311
312
313/* WRONG WRONG... better for VariableMap
314template <>
315template <>
316inline
317ReferenceT<JSONtree> & ReferenceT<JSONtree>::link(JSONtree &tree){
318 try {
319 //this->setPtr(p);
320 }
321 catch (const std::exception & e){
322 // Logger(__FILE__, __LINE__, __FUNCTION__).error("unsupported type: ", drain::TypeName<F>::str()); // , " msg:", e.what()
323 // Logger(__FILE__, __LINE__, __FUNCTION__).error("unsupported type: ", typeid(F).name(), " msg:", e.what());
324 // std::cerr << __FILE__ << ':' << __FUNCTION__ << ": unsupported type: " << typeid(F).name() << std::endl;
325 // throw std::runtime_error("unsupported type");
326 }
327 return *this;
328}
329*/
330
331class CheckJSON : public TreeVisitor<const JSONtree> {
332
333public:
334
335 virtual inline
336 int visitPrefix(const JSONtree & tree, const JSONtree::path_t & path){
337 const JSONtree & t = tree(path);
338 if (t.hasChildren() && !t.data.empty()){
339 std::cout << "JSON violation at '" << path << "': has child nodes and also non-empty data: " << t.data << '\n';
340 }
341 return 0;
342 }
343
344};
345
346} // drain
347
348#endif // DRAIN_JSON
Definition Castable.h:76
Definition JSON.h:331
Definition FileInfo.h:47
Utility for extracting JSON-compatible strings, numbers or arrays of numbers in text data.
Definition JSON.h:60
static void handleValue(std::istream &istr, T &tree, const std::string &key)
In reading trees.
Definition JSON.h:110
static void readValue(std::istream &istr, Castable &v, bool keepType=false)
Read a value (JSON syntax). Read stream until a value has been extracted, with type recognition.
Definition JSON.cpp:52
static std::ostream & treeToStream(std::ostream &ostr, const T &tree, const drain::SprinterLayout &layout=drain::Sprinter::jsonLayout, short indent=0)
Write a tree into an output stream using JSON layout by default.
Definition JSON.h:122
static void readTree(T &tree, std::istream &istr)
Reads and parses a JSON file.
Definition JSON.h:195
static void readArray(const std::string &s, Castable &v)
Given comma-separated string of values, assign them to variable of minimum compatible type.
Definition JSON.cpp:116
LogSourc e is the means for a function or any program segment to "connect" to a Log.
Definition Log.h:326
Logger & warn(const TT &... args)
Possible error, but execution can continue.
Definition Log.h:440
Logger & error(const TT &... args)
Echoes.
Definition Log.h:426
Logger & unimplemented(const TT &... args)
Feature to be done. Special type of Logger::note().
Definition Log.h:521
static std::ostream & toStream(std::ostream &ostr, const std::initializer_list< T > &x, const SprinterLayout &layout=defaultLayout)
New (experimental)
Definition Sprinter.h:423
static const SprinterLayout jsonLayout
Resembles JSON structure: {"a":1,"b":22,"c":3}.
Definition Sprinter.h:224
static char skipWhiteSpace(std::istream &istr)
Definition TextReader.h:90
static std::string scanSegment(std::istream &istr, const std::string &endChars)
Read input stream until any char in endChars is encountered. The end char will not be included,...
Definition TextReader.h:59
Default implementation of a tree visitor (concept) compatible TreeUtils::traverser()
Definition TreeUtils.h:266
Definition Data.h:1473
Definition Sprinter.h:136