Implemented simple json parsing reusing jsmn.

This commit is contained in:
Jose Marcial Vieira Bisneto 2018-10-25 19:00:32 -03:00
parent 35b20c9a2e
commit 94b782cfaa
No known key found for this signature in database
GPG key ID: 103E935E7E6E831E
3 changed files with 34 additions and 2 deletions

View file

@ -69,6 +69,7 @@ void jsmn_init(jsmn_parser *parser);
int jsmn_parse(jsmn_parser *parser, const char *js, size_t len,
jsmntok_t *tokens, unsigned int num_tokens);
char *jsmn_simple_parser(char *full_json, int json_len, char *key);
#ifdef __cplusplus
}
#endif

View file

@ -13,7 +13,7 @@
#include "ipfs/repo/fsrepo/fs_repo.h"
#include "libp2p/os/utils.h"
#include "ipfs/repo/fsrepo/lmdb_datastore.h"
#include "jsmn.h"
#include "ipfs/repo/fsrepo/jsmn.h"
#include "multiaddr/multiaddr.h"
/**

View file

@ -1,4 +1,6 @@
#include "jsmn.h"
#include "ipfs/repo/fsrepo/jsmn.h"
#include <string.h>
#include <stdlib.h>
/**
* Allocates a fresh unused token from the token pull.
@ -311,3 +313,32 @@ void jsmn_init(jsmn_parser *parser) {
parser->toknext = 0;
parser->toksuper = -1;
}
char *jsmn_simple_parser(char *full_json, int json_len, char *key) {
int num_tokens = 256, len, i;
if (!full_json || !key) {
return NULL;
}
jsmn_parser parser;
jsmn_init(&parser);
jsmntok_t tokens[num_tokens];
num_tokens = jsmn_parse(&parser, full_json, json_len, tokens, 256);
if (num_tokens <= 0) {
return NULL;
}
len = strlen(key);
for (i = 0; i < num_tokens; i++) {
jsmntok_t curr_token = tokens[i];
if (len == (curr_token.end - curr_token.start) && memcmp(full_json + curr_token.start, key, len) == 0) {
curr_token = tokens[i+1];
len = curr_token.end - curr_token.start;
char *ret = malloc(len + 1);
if (!ret) {
return NULL;
}
strncpy(ret, full_json + curr_token.start, len);
return ret;
}
}
return NULL;
}