#include #include #include #include #include "internal.h" enum json_parse_result parse_array(struct json **json_out, struct raw_json *raw, size_t depth) { assert(raw->data[raw->index] == '['); enum json_parse_result ret = JSON_PARSE_OK; struct json *json = NULL; struct json *obj = NULL; if (depth++ > 9) { ret = JSON_PARSE_MAX_DEPTH_ERR; goto err; } json = json_new_array(); if (!json) return JSON_OOM; do { raw->index++; skip_ws(raw); if (raw->data[raw->index] == ']') { if (json->children->nitems == 0) { break; } ret = JSON_PARSE_EXPECTED_VALUE_ERR; goto err; } ret = parse_value(&obj, raw, depth); if (ret != JSON_PARSE_OK) { goto err; } json_array_append(json, obj); skip_ws(raw); obj = NULL; } while (raw->index < raw->size && raw->data[raw->index] == ','); if (raw->data[raw->index] != ']') { ret = JSON_PARSE_INVALID_TOKEN_ERR; goto err; } raw->index++; *json_out = json; goto end; err: json_delete(json); json_delete(obj); end: return ret; } bool json_array_append(struct json *dest, struct json *src) { if (!dest || !src) return false; add_children(dest, src); return true; } struct json *json_array_get(const struct json *json, size_t index) { if (index > json->children->nitems) return NULL; return json->children->items[index]; } struct json *json_array_add_object(struct json *dest) { struct json *obj = json_new_object(); json_array_append(dest, obj); return obj; } struct json *json_array_add_array(struct json *dest) { struct json *array = json_new_array(); json_array_append(dest, array); return array; } struct json *json_array_add_number(struct json *dest, double num) { struct json *number = json_new_number(num); json_array_append(dest, number); return number; } struct json *json_array_add_string(struct json *dest, const char *string) { struct json *str = json_new_string_copy(string); json_array_append(dest, str); return str; } struct json *json_array_add_bool(struct json *dest, bool boolean) { struct json *b = json_new_bool(boolean); json_array_append(dest, b); return b; } struct json *json_array_add_null(struct json *dest) { struct json *n = json_new_null(); json_array_append(dest, n); return n; } struct json *json_array_detach(struct json *json, size_t index) { if (json->type != JSON_ARRAY || index >= json->children->nitems) { return NULL; } struct json *tmp = json->children->items[index]; json_detach(tmp); return tmp; } void json_array_delete(struct json *json, size_t index) { struct json *tmp = json_array_detach(json, index); json_delete(tmp); }