blob: c36559c98139e39d4707e1aa0845c0f38f392e02 [file] [log] [blame]
Austin Schuhf417eaf2019-09-16 21:58:36 -07001//
2// This is a simple example of running the tokenizer, outputting information
3// to stdout about what tokens we get and their values.
4//
5#include <jsont.h>
6#include <stdio.h>
7#include <string.h>
8
9static const char* _tok_name(jsont_tok_t tok);
10
11int main(int argc, const char** argv) {
12 // Create a new reusable tokenizer
13 jsont_ctx_t* S = jsont_create(0);
14
15 // Sample input
16 const char* inbuf = "{\"Ape\":123,\"Bro\":[400192,\"51\",true, false, null,"
17 " -67,\r\n\t 6.123]}";
18
19 // Reset the parser with a pointer to our sample input
20 jsont_reset(S, (const uint8_t*)inbuf, strlen(inbuf));
21
22 // Read each token
23 jsont_tok_t tok;
24 printf("Token | Value\n"
25 "-------------|----------------------------------------\n");
26 while ( (tok = jsont_next(S)) != JSONT_END && tok != JSONT_ERR) {
27 printf("%-12s |", _tok_name(tok));
28
29 // If the token has a value, also print its value
30 if (tok == JSONT_STRING || tok == JSONT_FIELD_NAME) {
31 const uint8_t* bytes = 0;
32 size_t len = jsont_data_value(S, &bytes);
33 if (len != 0)
34 printf(" '%.*s'", (int)len, (const char*)bytes);
35 } else if (tok == JSONT_NUMBER_INT) {
36 printf(" %lld", jsont_int_value(S));
37 } else if (tok == JSONT_NUMBER_FLOAT) {
38 printf(" %f", jsont_float_value(S));
39 }
40
41 printf("\n");
42 }
43
44 // If we got an error, print some useful information and exit with 1
45 if (tok == JSONT_ERR) {
46 fprintf(stderr, "Error: %s ('%c' at offset %lu)\n",
47 jsont_error_info(S),
48 (char)jsont_current_byte(S),
49 (unsigned long)jsont_current_offset(S));
50 return 1;
51 }
52
53 // Destroy our reusable tokenizer and exit
54 jsont_destroy(S);
55 return 0;
56}
57
58// Utility to get a printable name for a token
59static const char* _tok_name(jsont_tok_t tok) {
60 switch (tok) {
61 case JSONT_END: return "END";
62 case JSONT_ERR: return "ERR";
63 case JSONT_OBJECT_START: return "OBJECT_START";
64 case JSONT_OBJECT_END: return "OBJECT_END";
65 case JSONT_ARRAY_START: return "ARRAY_START";
66 case JSONT_ARRAY_END: return "ARRAY_END";
67 case JSONT_TRUE: return "TRUE";
68 case JSONT_FALSE: return "FALSE";
69 case JSONT_NULL: return "NULL";
70 case JSONT_NUMBER_INT: return "NUMBER_INT";
71 case JSONT_NUMBER_FLOAT: return "NUMBER_FLOAT";
72 case JSONT_STRING: return "STRING";
73 case JSONT_FIELD_NAME: return "FIELD_NAME";
74 default: return "?";
75 }
76}