Skip to content

Commit a651659

Browse files
committed
initial commit
1 parent 33ba2aa commit a651659

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

arduino/libraries/jsonlib.cpp

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include "jsonlib.h"
2+
3+
String jsonIndexList(String json, int idx){
4+
int count = 1; // number of braces seen { = +1 } = -1
5+
int i = 1;
6+
int item_idx = 0;
7+
int start = i;
8+
int stop = json.length() - 1;
9+
10+
while(i < json.length() && count > 0){
11+
if(json.charAt(i) == ']' or json.charAt(i) == '}'){
12+
count--;
13+
}
14+
if(json.charAt(i) == '{' or json.charAt(i) == '['){
15+
count++;
16+
}
17+
if(count == 1 && json.charAt(i) == ',' && item_idx == idx){
18+
//item separator!
19+
stop = i;
20+
return json.substring(start, stop);
21+
}
22+
if(count == 1 && json.charAt(i) == ']' && item_idx == idx){
23+
stop = i + 1;
24+
return json.substring(start, stop);
25+
}
26+
if(count == 1 && json.charAt(i) == ','){
27+
item_idx++;
28+
start = i + 1;
29+
}
30+
i++;
31+
}
32+
return json.substring(start, stop);
33+
}
34+
35+
// return a sub-json struct
36+
String jsonExtract(String json, String name){
37+
char next;
38+
int start, stop;
39+
40+
name = String("\"") + name + String("\"");
41+
start = json.indexOf(name) + name.length() + 1;
42+
next = json.charAt(start);
43+
if(next == '\"'){
44+
//Serial.println(".. a string");
45+
start = start + 1;
46+
stop = json.indexOf('"', start + 1);
47+
}
48+
else if(next == '['){
49+
//Serial.println(".. a list");
50+
int count = 1;
51+
int i = start;
52+
while(count > 0 && i++ < json.length()){
53+
if(json.charAt(i) == ']'){
54+
count--;
55+
}
56+
else if(json.charAt(i) == '['){
57+
count++;
58+
}
59+
}
60+
stop = i + 1;
61+
}
62+
else if(next == '{'){
63+
//Serial.println(".. a struct");
64+
int count = 1;
65+
int i = start;
66+
while(count > 0 && i++ < json.length()){
67+
if(json.charAt(i) == '}'){
68+
count--;
69+
}
70+
else if(json.charAt(i) == '{'){
71+
count++;
72+
}
73+
}
74+
stop = i + 1;
75+
}
76+
else if(next == '.' || next == '-' || ('0' <= next && next <= '9')){
77+
//Serial.println(".. a number");
78+
int i = start;
79+
while(i++ < json.length() && json.charAt(i) == '.' || ('0' <= json.charAt(i) && json.charAt(i) <= '9')){
80+
}
81+
stop = i;
82+
}
83+
return json.substring(start, stop);
84+
}
85+

arduino/libraries/jsonlib.h

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#ifndef JSONLIB_H
2+
#define JSONLIB_H
3+
4+
#include <Arduino.h>
5+
6+
String jsonIndexList(String json, int idx);
7+
String jsonExtract(String json, String name);
8+
9+
#endif

0 commit comments

Comments
 (0)