32 #include "jsonparse.h"
38 push(
struct jsonparse_state *state,
char c)
40 state->stack[state->depth] = c;
43 return state->depth < JSONPARSE_MAX_DEPTH;
47 pop(
struct jsonparse_state *state)
49 if(state->depth == 0) {
50 return JSON_TYPE_ERROR;
53 return state->stack[state->depth];
60 atomic(
struct jsonparse_state *state,
char type)
64 state->vstart = state->pos;
66 if(type == JSON_TYPE_STRING || type == JSON_TYPE_PAIR_NAME) {
67 while((c = state->json[state->pos++]) && c !=
'"') {
72 state->vlen = state->pos - state->vstart - 1;
73 }
else if(type == JSON_TYPE_NUMBER) {
75 c = state->json[state->pos];
76 if((c < '0' || c >
'9') && c !=
'.') {
84 state->vlen = state->pos - state->vstart;
90 skip_ws(
struct jsonparse_state *state)
94 while(state->pos < state->len &&
95 ((c = state->json[state->pos]) ==
' ' || c ==
'\n')) {
101 jsonparse_setup(
struct jsonparse_state *state,
const char *json,
int len)
112 jsonparse_next(
struct jsonparse_state *state)
118 c = state->json[state->pos];
119 s = jsonparse_get_type(state);
127 if(s ==
':' && state->vtype != 0) {
130 s = jsonparse_get_type(state);
135 state->error = JSON_ERROR_SYNTAX;
136 return JSON_TYPE_ERROR;
143 state->error = JSON_ERROR_UNEXPECTED_END_OF_ARRAY;
144 return JSON_TYPE_ERROR;
152 if(s ==
':' && state->vtype != 0) {
154 }
else if(s ==
'[') {
157 state->error = JSON_ERROR_SYNTAX;
158 return JSON_TYPE_ERROR;
162 if(s ==
'{' || s ==
'[' || s ==
':') {
163 atomic(state, c = (s ==
'{' ? JSON_TYPE_PAIR_NAME : c));
165 state->error = JSON_ERROR_UNEXPECTED_STRING;
166 return JSON_TYPE_ERROR;
170 if(s ==
'{' || s ==
'[' || s ==
':') {
173 state->error = JSON_ERROR_UNEXPECTED_ARRAY;
174 return JSON_TYPE_ERROR;
178 if(s ==
':' || s ==
'[') {
179 if(c <= '9' && c >=
'0') {
180 atomic(state, JSON_TYPE_NUMBER);
181 return JSON_TYPE_NUMBER;
193 jsonparse_copy_value(
struct jsonparse_state *state,
char *str,
int size)
197 if(state->vtype == 0) {
200 size = size <= state->vlen ? (size - 1) : state->vlen;
201 for(i = 0; i < size; i++) {
202 str[i] = state->json[state->vstart + i];
209 jsonparse_get_value_as_int(
struct jsonparse_state *state)
211 if(state->vtype != JSON_TYPE_NUMBER) {
214 return atoi(&state->json[state->vstart]);
218 jsonparse_get_value_as_long(
struct jsonparse_state *state)
220 if(state->vtype != JSON_TYPE_NUMBER) {
223 return atol(&state->json[state->vstart]);
229 jsonparse_strcmp_value(
struct jsonparse_state *state,
const char *str)
231 if(state->vtype == 0) {
234 return strncmp(str, &state->json[state->vstart], state->vlen);
238 jsonparse_get_len(
struct jsonparse_state *state)
244 jsonparse_get_type(
struct jsonparse_state *state)
246 if(state->depth == 0) {
249 return state->stack[state->depth - 1];
253 jsonparse_has_next(
struct jsonparse_state *state)
255 return state->pos < state->len;