Turi Create  4.0
json_util.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef TURI_UNITY_JSON_UTIL_HPP
7 #define TURI_UNITY_JSON_UTIL_HPP
8 #include <core/data/json/json_include.hpp>
9 #include <model_server/lib/api/client_base_types.hpp>
10 #include <cmath>
11 namespace turi {
12  /**
13  * Helper utility for converting from flexible_type to json.
14  * TODO: Fill in details
15  */
16  inline JSONNode flexible_type_to_json(const flexible_type& val, std::string name) {
17 
18  if (val.get_type() == flex_type_enum::INTEGER) {
19  // long cast needed to avoid a ambiguity error which seems to only show up
20  // on mac clang++
21  if (std::isnan(val.get<flex_int>())) {
22  // treat nan as missing value null
23  JSONNode v(JSON_NULL);
24  v.set_name(name);
25  v.nullify();
26  return v;
27  } else {
28  return JSONNode(name, (double)val.get<flex_int>());
29  }
30  } else if (val.get_type() == flex_type_enum::FLOAT) {
31  if (std::isnan(val.get<double>())) {
32  // treat nan as missing value null
33  JSONNode v(JSON_NULL);
34  v.set_name(name);
35  v.nullify();
36  return v;
37  } else {
38  return JSONNode(name, val.get<double>());
39  }
40  } else if (val.get_type() == flex_type_enum::STRING) {
41  return JSONNode(name, val.get<flex_string>());
42  } else if (val.get_type() == flex_type_enum::VECTOR) {
43  const std::vector<double>& v = val.get<flex_vec>();
44  JSONNode vec(JSON_ARRAY);
45  for (size_t i = 0;i < v.size(); ++i) {
46  JSONNode vecval(JSON_NUMBER);
47  vecval= v[i];
48  vec.push_back(vecval);
49  }
50  vec.set_name(name);
51  return vec;
52  } else if (val.get_type() == flex_type_enum::DICT){
53  return JSONNode(name, val.get<flex_string>());
54  } else if (val.get_type() == flex_type_enum::UNDEFINED){
55  JSONNode v(JSON_NULL);
56  v.set_name(name);
57  v.nullify();
58  return v;
59  }
60 
61  JSONNode v(JSON_NULL);
62  v.set_name(name);
63  v.nullify();
64  return v;
65  }
66 
67 }
68 #endif
std::vector< double > flex_vec
const T & get() const
flex_type_enum get_type() const
std::string flex_string
JSONNode flexible_type_to_json(const flexible_type &val, std::string name)
Definition: json_util.hpp:16