diff --git a/examples/simple_parse.c b/examples/simple_parse.c new file mode 100644 index 0000000..945cf0f --- /dev/null +++ b/examples/simple_parse.c @@ -0,0 +1,196 @@ +/* + * Simple example of parsing and printing JSON using jansson. + * + * SYNOPSIS: + * $ examples/simple_parse + * Type some JSON > [true, false, null, 1, 0.0, -0.0, "", {"name": "barney"}] + * JSON Array of 8 elements: + * JSON True + * JSON False + * JSON Null + * JSON Integer: "1" + * JSON Real: 0.000000 + * JSON Real: -0.000000 + * JSON String: "" + * JSON Object of 1 pair: + * JSON Key: "name" + * JSON String: "barney" + * + * Copyright (c) 2014 Robert Poor + * + * Jansson is free software; you can redistribute it and/or modify + * it under the terms of the MIT license. See LICENSE for details. + */ + +#include +#include +#include "jansson.h" + +/* forward refs */ +void print_json(json_t *root); +void print_json_aux(json_t *element, int indent); +void print_json_indent(int indent); +const char *json_plural(int count); +void print_json_object(json_t *element, int indent); +void print_json_array(json_t *element, int indent); +void print_json_string(json_t *element, int indent); +void print_json_integer(json_t *element, int indent); +void print_json_real(json_t *element, int indent); +void print_json_true(json_t *element, int indent); +void print_json_false(json_t *element, int indent); +void print_json_null(json_t *element, int indent); + +void print_json(json_t *root) { + print_json_aux(root, 0); +} + +void print_json_aux(json_t *element, int indent) { + switch json_typeof(element) { + case JSON_OBJECT: + print_json_object(element, indent); + break; + case JSON_ARRAY: + print_json_array(element, indent); + break; + case JSON_STRING: + print_json_string(element, indent); + break; + case JSON_INTEGER: + print_json_integer(element, indent); + break; + case JSON_REAL: + print_json_real(element, indent); + break; + case JSON_TRUE: + print_json_true(element, indent); + break; + case JSON_FALSE: + print_json_false(element, indent); + break; + case JSON_NULL: + print_json_null(element, indent); + break; + default: + fprintf(stderr, "unrecognized JSON type %d\n", json_typeof(element)); + } +} + +void print_json_indent(int indent) { + for (int i=0; i "); + fflush(stdout); + return fgets(line, max_chars, stdin); +} + +/* ================================================================ + * main + */ + +#define MAX_CHARS 4096 + +int main(int argc, char *argv[]) { + char line[MAX_CHARS]; + + if (argc != 1) { + fprintf(stderr, "Usage: %s\n", argv[0]); + exit(-1); + } + + while (read_line(line, MAX_CHARS) != (char *)NULL) { + + /* parse text into JSON structure */ + json_t *root = load_json(line); + + if (root) { + /* print and release the JSON structure */ + print_json(root); + json_decref(root); + } + } + + return 0; +}