-
Notifications
You must be signed in to change notification settings - Fork 2
/
json.h
136 lines (124 loc) · 2.74 KB
/
json.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*
* author : Shuichi TAKANO
* since : Sun Sep 08 2019 13:33:0
*/
#ifndef B8E6F323_8134_16B4_CB67_1557554CB380
#define B8E6F323_8134_16B4_CB67_1557554CB380
#include <assert.h>
#include <experimental/optional>
#include <string>
#include <stdio.h>
#include <vector>
#include <sd_card/ff.h>
#define PICOJSON_ASSERT(x) assert(x)
#define PICOJSON_OVERFLOW(str) assert(!str)
#include <picojson.h>
inline std::experimental::optional<picojson::value>
parseJSONFile(const std::string &filename)
{
#if 0
FILE *fp = fopen(filename.c_str(), "r");
if (!fp)
{
printf("JSON file read failed.\n");
return {};
}
fseek(fp, SEEK_END, 0);
std::vector<uint8_t> buffer(ftell(fp));
fseek(fp, SEEK_SET, 0);
fread(buffer.data(), buffer.size(), 1, fp);
fclose(fp);
#else
FIL f;
if (f_open(&f, filename.c_str(), FA_READ) != FR_OK)
{
printf("JSON file read failed.\n");
return {};
}
std::vector<uint8_t> buffer(f_size(&f));
UINT br;
f_read(&f, buffer.data(), buffer.size(), &br);
f_close(&f);
#endif
picojson::value root;
std::string err;
parse(root, buffer.begin(), buffer.end(), &err);
if (!err.empty())
{
printf("JSON file parse error. (%s)\n", err.c_str());
return {};
}
return root;
}
inline std::experimental::optional<picojson::value>
get(const picojson::value &obj, const char *name)
{
auto v = obj.get(name);
if (v.is<picojson::null>())
{
return {};
}
return v;
}
template <class T>
inline std::experimental::optional<T>
get(const picojson::value &v)
{
if (v.is<T>())
{
return v.get<T>();
}
return {};
}
template <class T>
inline std::experimental::optional<T>
getValue(const picojson::value &obj, const char *name)
{
if (auto v = get(obj, name))
{
if (auto val = get<T>(*v))
{
return val;
}
else
{
printf("invalid JSON value '%s'\n", name);
}
}
return {};
}
template <class T>
inline T
getValue(const picojson::value &obj, const char *name, T default_val)
{
if (auto v = getValue<T>(obj, name))
{
return *v;
}
return default_val;
}
inline std::experimental::optional<int>
getInt(const picojson::value &obj, const char *name)
{
if (auto v = getValue<double>(obj, name))
{
return (int)*v;
}
return {};
}
inline int
getInt(const picojson::value &obj, const char *name, int default_val)
{
if (auto v = getInt(obj, name))
{
return *v;
}
return default_val;
}
template <>
inline std::experimental::optional<int>
getValue<int>(const picojson::value &obj, const char *name)
{
return getInt(obj, name);
}
#endif /* B8E6F323_8134_16B4_CB67_1557554CB380 */