JSON.h
1 /*
2 
3 MIT License
4 
5 Copyright (c) 2017 FMI Open Development / Markus Peura, first.last@fmi.fi
6 
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13 
14 The above copyright notice and this permission notice shall be included in all
15 copies or substantial portions of the Software.
16 
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 SOFTWARE.
24 
25 */
26 /*
27 Part of Rack development has been done in the BALTRAD projects part-financed
28 by the European Union (European Regional Development Fund and European
29 Neighbourhood 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 
44 namespace 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  */
60 class JSON {
61 
62 public:
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 
105 protected:
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 
121 template <class T>
122 std::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();
126 
127  if (! (DATA||CHILDREN)){
128  // Also empty element should return something, here {}, but could be "" or null ?
129  ostr << layout.mapChars.prefix << layout.mapChars.suffix; // '\n';
130  return ostr;
131  }
132 
133  const std::string pad(2*indent, ' ');
134 
135  if (DATA){
136  drain::Sprinter::toStream(ostr, tree.data, layout);
137  //ostr << layout.pairChars.suffix;
138  return ostr; // = pratically exclusive
139  /*
140  if (CHILDREN)
141  ostr << layout.mapChars.separator;
142  ostr << '\n';
143  */
144  }
145 
146  ostr << layout.mapChars.prefix; // << '\n';
147  //ostr << layout.pairChars.prefix;
148  ostr << '\n';
149 
150  if (CHILDREN){
151  char sep = 0;
152  for (const auto & entry: tree){
153  if (sep){
154  ostr << sep;
155  ostr << '\n';
156  }
157  else {
158  sep = layout.mapChars.separator;
159  }
160  //ostr << pad << " " << '"' << entry.first << '"' << layout.pairChars.separator << ' '; // if empty?
161  ostr << pad << " "; // if empty?
162  // if (layout.pairChars.prefix)
163  ostr << layout.pairChars.prefix;
164  ostr << '"' << entry.first << '"' << layout.pairChars.separator << ' '; // if empty?
165  treeToStream(ostr, entry.second, layout, indent+1); // recursion
166  // if (layout.pairChars.suffix)
167  ostr << layout.pairChars.suffix;
168  }
169  ostr << '\n';
170  }
171 
172  // if (layout.mapChars.suffix)
173  ostr << pad << layout.mapChars.suffix; // << '\n';
174 
175  return ostr;
176 }
177 
178 template <class T>
179 void JSON::readTree(T & tree, std::istream & istr){
180 
181  drain::Logger log(__FILE__, __FUNCTION__);
182 
183 
184  if (!istr){
185  log.error("File read error");
186  return;
187  }
188 
189  char c;
190 
192  c = istr.get();
193  if (c != '{'){
194  log.error("Syntax error: read '", c, "' when expecting '{'");
195  return;
196  }
197 
198  std::string key;
199  std::string value;
200 
201  // Debugging. Incomplete segments raise warnings.
202  bool completed = true; //
203 
204  while (istr){
205 
207 
208  if (!istr)
209  return;
210 
211  c = istr.get();
212 
213  if (c == '"'){ // New key, starting new entry
214 
215  key = TextReader::scanSegment(istr, "\"");
216  istr.get(); // swallow '"'
218  c = istr.get();
219  // log.warn() << " then4: " << (char)istr.peek() << log.endl;
220 
221  if (c == ':'){
222  //handleValue(istr, tree, key);
223 
224  handleValue(istr, tree, key);
225  // log.note(" - end: ", key);
226  completed = true;
227  }
228  else {
229  log.error() << "Syntax error: read \"" << key << "\" followed by '" << c << "' when expecting object {...}, string \"...\", array [...], or number" << log.endl;
230  return;
231  }
232  }
233  else if (c == '}'){
234  if (!completed) // comma encountered after empty segment
235  log.warn("empty section after key=", key);
236  //log.warn("closing '}' for ", key);
237  return;
238  }
239  else if (c == ','){
240  //if (!completed) // comma encountered after empty segment
241  // log.warn("empty section after key=", key);
242  completed = false; // trap for subsequent check
243  }
244  else { // TODO: warn if comma encountered after empty
245  log.error("Syntax error: char '", c, "' (", (short)c, "), expected '\"', '}' or ','");
246  return;
247  }
248 
249  }
250 
251 }
252 
253 
254 // New 2023 "implementation"
255 typedef drain::UnorderedMultiTree<drain::Variable,true> JSONtree2;
256 
257 
258 template <>
259 inline
260 void drain::JSON::handleValue(std::istream & istr, JSONtree2 & dst, const std::string & key){
261 //void drain::JSON::handleValue(std::istream & istr, JSONtree2 & child){
262 
263  drain::Logger log( __FILE__, __FUNCTION__);
264 
265 
266  JSONtree2 & child = dst.addChild(key);
267 
269 
270  char c = istr.peek();
271 
272  if (c == '{'){
273  // log.warn("Reading object '", key, "'");
274  JSON::readTree(child, istr);
275  }
276  else {
277  // log.warn("Reading value '", key, "'");
278  JSON::readValue(istr, child.data);
279  }
280 
281  return;
282 }
283 
284 
285 
286 template <>
287 inline
288 std::ostream & drain::Sprinter::toStream(std::ostream & ostr, const JSONtree2 & tree, const drain::SprinterLayout & layout){
289  return drain::JSON::treeToStream(ostr, tree, layout);
290  //return drain::Sprinter::treeToStream(ostr, tree, layout);
291 }
292 
293 
294 /* WRONG WRONG... better for VariableMap
295 template <>
296 template <>
297 inline
298 ReferenceT<JSONtree2> & ReferenceT<JSONtree2>::link(JSONtree2 &tree){
299  try {
300  //this->setPtr(p);
301  }
302  catch (const std::exception & e){
303  // Logger(__FILE__, __LINE__, __FUNCTION__).error("unsupported type: ", drain::TypeName<F>::str()); // , " msg:", e.what()
304  // Logger(__FILE__, __LINE__, __FUNCTION__).error("unsupported type: ", typeid(F).name(), " msg:", e.what());
305  // std::cerr << __FILE__ << ':' << __FUNCTION__ << ": unsupported type: " << typeid(F).name() << std::endl;
306  // throw std::runtime_error("unsupported type");
307  }
308  return *this;
309 }
310 */
311 
312 } // drain
313 
314 #endif // DRAIN_JSON
Definition: Castable.h:76
Definition: FileInfo.h:48
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:179
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:308
Logger & error(const TT &... args)
Echoes.
Definition: Log.h:412
Logger & unimplemented(const TT &... args)
Feature to be done. Special type of Logger::note().
Definition: Log.h:507
Logger & warn(const TT &... args)
Possible error, but execution can continue.
Definition: Log.h:426
static std::ostream & toStream(std::ostream &ostr, const std::initializer_list< T > &x, const SprinterLayout &layout=defaultLayout)
New (experimental)
Definition: Sprinter.h:420
static const SprinterLayout jsonLayout
Resembles JSON structure: {"a":1,"b":22,"c":3}.
Definition: Sprinter.h:221
static char skipWhiteSpace(std::istream &istr)
Definition: TextReader.h:91
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:60
Definition: DataSelector.cpp:1277
Definition: Sprinter.h:137