-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnjson.cpp
More file actions
349 lines (328 loc) · 9.62 KB
/
njson.cpp
File metadata and controls
349 lines (328 loc) · 9.62 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#include <string.h>
#include "njson.h"
/*!\brief Removes whitespace from input string
* \param buffer JSON string to trim
* \return Trimmed JSON string without whitespace
*/
std::string njson::trim(std::string buffer){
bool quoted=false;
bool escaped=false;
size_t size=0;
for(unsigned i=0;i<buffer.size();i++){
// Track quotation and escaped characters
if(quoted && escaped){
escaped=false;
}
else if(quoted && buffer[i]=='\"'){
quoted=false;
}
else if(!quoted && buffer[i]=='\"'){
quoted=true;
}
if(!quoted && std::isspace(buffer[i])){
// Drop unquoted whitespace
}
else{
// Keep everything else
escaped=(buffer[i]=='\\');
buffer[size++]=buffer[i];
}
}
return buffer.substr(0,size);
}
/*!\brief Parses a quoted string
* \param buffer JSON string containing quoted string
* \param pos Position in buffer to start search
* \return Found quoted string
*
* Throws njson_exception upon error
*/
std::string njson::parsequoted(std::string buffer,const int &pos){
bool escaped=false;
if(buffer[pos]!='\"') throw njson_exception("Expected quoted string");
for(unsigned i=pos+1;i<buffer.size();i++){
// Track quotation and escaped characters
if(escaped){
escaped=false;
}
else if(buffer[i]=='\"'){
return buffer.substr(pos,i-pos+1);
}
else if(buffer[i]=='\\'){
escaped=true;
}
}
throw njson_exception("String was not quoted");
}
/*!\brief Parses an unquoted string
* \param buffer JSON string containing string
* \param pos Position in buffer to start search
* \return Found string
*
* Throws njson_exception upon error
*/
std::string njson::parseunquoted(std::string buffer,const int &pos){
for(unsigned i=pos;i<buffer.size();i++){
if(buffer[i]==',' || buffer[i]=='}'){
return buffer.substr(pos,i-pos);
}
}
return buffer.substr(pos);
}
/*!\brief Parses a json block value
* \param buffer JSON string containing [] or {} block
* \param pos Position in buffer to start search
* \return Found block
*
* Throws njson_exception upon error
*/
std::string njson::parseblock(std::string buffer,const int &pos){
// Check bracket type
char end=0,beg=buffer[pos];
if(beg=='{') end='}';
if(beg=='[') end=']';
// Parse block
bool quoted=false;
bool escaped=false;
int depth=0;
for(unsigned i=pos+1;i<buffer.size();i++){
// Track quotation and escaped characters
if(quoted && escaped){
escaped=false;
}
else if(quoted && buffer[i]=='\"'){
quoted=false;
}
else if(!quoted && buffer[i]=='\"'){
quoted=true;
}
if(quoted){
escaped=(buffer[i]=='\\');
}
else{
// Check for brackets
if(buffer[i]==beg){
depth++;
}
else if(buffer[i]==end){
if(depth--==0){
return buffer.substr(pos,i-pos+1);
}
}
}
}
if(beg=='{') throw njson_exception("JSON object incorrectly formatted");
if(beg=='[') throw njson_exception("JSON array incorrectly formatted");
throw njson_exception("Invalid JSON block formatting");
}
/*!\brief Parses a json array
* \param object ndict object to populate with members
* \param buffer JSON string containing [] block
*
* Throws njson_exception upon error
*/
void njson::parsearray(ndict &object,std::string buffer){
// Remove outer brackets
if(buffer[0]!='[' || buffer[buffer.size()-1]!=']'){
throw njson_exception("Invalid JSON array formatting");
}
buffer=buffer.substr(1,buffer.size()-2);
// Parse block
bool quoted=false;
int odepth=0;
std::vector<std::string> array;
std::string value;
object=array;
for(unsigned i=0;i<buffer.size();i++){
// Track quotation and escaped characters
if(!odepth){
if(quoted && buffer[i]=='\"'){
quoted=false;
}
else if(!quoted && buffer[i]=='\"'){
quoted=true;
}
}
// Track object depth
if(!quoted){
if(buffer[i]=='{' || buffer[i]=='['){
odepth++;
}
if(odepth && (buffer[i]=='}' || buffer[i]==']')){
odepth--;
}
}
// Check for separator
if(!quoted && !odepth && buffer[i]==','){
array.push_back(value);
value.clear();
}
else{
value+=buffer[i];
}
}
if(value.size()){
array.push_back(value);
}
for(unsigned i=0;i<array.size();i++){
parsevalue(object[i],array[i]);
}
}
/*!\brief Finds type of value by formatting
* \param buffer String with JSON-formatted value
* \return ndict enumeration value
*/
ndict::type_t njson::valuetype(std::string buffer){
if(buffer.size()){
if(buffer[0]=='{'){
return ndict::TOBJECT;
}
else if(buffer[0]=='['){
return ndict::TARRAY;
}
else if(buffer[0]=='\"'){
return ndict::TSTRING;
}
else if(std::isdigit(buffer[0]) || buffer[0]=='-'){
return ndict::TNUMBER;
}
else{
std::string v=buffer;
std::transform(v.begin(),v.end(),v.begin(),::toupper);
if(v=="TRUE" || v=="FALSE"){
return ndict::TBOOL;
}
if(v=="NULL"){
return ndict::TNULL;
}
throw njson_exception(std::string("Invalid JSON value: ")+buffer);
}
}
return ndict::TNULL;
}
/*!\brief Assigns a value with the correct type
* \param object ndict object to populate with members
* \param buffer String with JSON-formatted value
*/
void njson::parsevalue(ndict &object,std::string buffer){
ndict::type_t type=valuetype(buffer);
if(type==ndict::TNUMBER){
if(buffer.find(".")==std::string::npos){
object=atoi(buffer.c_str());
}
else{
object=atof(buffer.c_str());
}
}
if(type==ndict::TSTRING){
object=buffer.substr(1,buffer.size()-2);
}
if(type==ndict::TBOOL){
std::string v=buffer;
std::transform(v.begin(),v.end(),v.begin(),::toupper);
object=(v=="TRUE")?true:false;
}
if(type==ndict::TARRAY){
parsearray(object,buffer);
}
if(type==ndict::TOBJECT){
parseobject(object,buffer);
}
}
/*!\brief Parses a json object
* \param object ndict object to populate with members
* \param buffer JSON string containing {} block
*
* Throws njson_exception upon error
*/
void njson::parseobject(ndict &object,std::string buffer){
// Remove outer brackets
if(buffer[0]!='{' || buffer[buffer.size()-1]!='}'){
throw njson_exception("Invalid JSON object formatting");
}
buffer=buffer.substr(1,buffer.size()-2);
// Parse keyed values
unsigned pos=0;
while(pos<buffer.size()){
// Parse key
std::string value,key=parsequoted(buffer,pos);
pos+=key.size();
if(buffer[pos++]!=':'){
throw njson_exception("Key and value must be separated by :");
}
// Parse value
switch(buffer[pos]){
case '\"': value=parsequoted(buffer,pos); break;
case '{': value=parseblock(buffer,pos); break;
case '[': value=parseblock(buffer,pos); break;
default: value=parseunquoted(buffer,pos);break;
}
pos+=value.size();
if(buffer[pos]==',') pos++;
// Load key:value
key=key.substr(1,key.size()-2);
if(value[0]=='['){
parsearray(object[key],value);
}
else if(value[0]=='{'){
parseobject(object[key],value);
}
else{
parsevalue(object[key],value);
}
}
}
/*!\brief Reads a JSON string from a file and decodes the input to a dictionary object
* \param path Path to JSON file to read
* \return ndict object of the decoded file
*
* Throws njson_exception upon error
*/
ndict njson::read(const std::string &path){
FILE *fd=fopen(path.c_str(),"r");
if(fd){
fseek(fd,0,SEEK_END);
size_t size=ftell(fd);
fseek(fd,0,SEEK_SET);
char buffer[size+1];
size=fread(buffer,1,size,fd);
fclose(fd);
buffer[size]=0;
return decode(buffer);
}
else{
throw njson_exception(std::string("Failed to open input file: ")+strerror(errno));
}
}
/*!\brief Decodes a JSON string to a dictionary object
* \param json String containing JSON text to be decoded
* \return ndict object of the decoded string
*
* Throws njson_exception upon error
*/
ndict njson::decode(const std::string &json){
ndict object;
std::string buffer=trim(json);
parseobject(object,buffer);
return object;
}
/*!\brief Encodes a dictionary object as a JSON string
* \param dict Dictionary object to encode
* \return JSON string representing the dictionary object
*/
std::string njson::encode(const ndict &dict){
return dict.getjson();
}
/*!\brief Merges a JSON string with a dictionary object
* \param json JSON string to decode and merge
* \param dict Dictionary object to merge with
* \return A new merged object
*
* Throws njson_exception upon decoding errors
*/
ndict njson::merge(const std::string &json,const ndict &dict){
ndict newdict=decode(json);
ndict mrgdict=dict;
mrgdict.merge(newdict);
return mrgdict;
}