common/json: restore json_delve() for simple plugin parsing.

This was removed (as unused) in 6269a4c55d592e8720b7f2a304c21f61f7931238;
now I've even added tests.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
This commit is contained in:
Rusty Russell
2018-12-16 15:14:06 +10:30
parent 3773251d4e
commit adf08f8914
3 changed files with 135 additions and 0 deletions

View File

@@ -4,6 +4,7 @@
#include <ccan/build_assert/build_assert.h>
#include <ccan/str/hex/hex.h>
#include <ccan/tal/str/str.h>
#include <common/utils.h>
#include <errno.h>
#include <inttypes.h>
#include <stdarg.h>
@@ -273,3 +274,39 @@ void json_tok_remove(jsmntok_t **tokens, jsmntok_t *tok, size_t num)
tal_resize(tokens, tal_count(*tokens) - remove_count);
(*tokens)->size -= num;
}
const jsmntok_t *json_delve(const char *buffer,
const jsmntok_t *tok,
const char *guide)
{
while (*guide) {
const char *key;
size_t len = strcspn(guide+1, ".[]");
key = tal_strndup(tmpctx, guide+1, len);
switch (guide[0]) {
case '.':
if (tok->type != JSMN_OBJECT)
return NULL;
tok = json_get_member(buffer, tok, key);
if (!tok)
return NULL;
break;
case '[':
if (tok->type != JSMN_ARRAY)
return NULL;
tok = json_get_arr(tok, atol(key));
if (!tok)
return NULL;
/* Must be terminated */
assert(guide[1+strlen(key)] == ']');
len++;
break;
default:
abort();
}
guide += len + 1;
}
return tok;
}