Skip to content

Commit b8f726c

Browse files
committed
Add json_parser library
1 parent d639aa2 commit b8f726c

File tree

8 files changed

+4388
-2
lines changed

8 files changed

+4388
-2
lines changed

CMakeLists.txt

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# author Eray Ozturk | erayozturk1@gmail.com
2+
# url github.com/diffstorm
3+
cmake_minimum_required(VERSION 3.12)
4+
project(json_parser LANGUAGES C CXX)
5+
6+
set(CMAKE_C_STANDARD 11)
7+
set(CMAKE_C_STANDARD_REQUIRED ON)
8+
set(CMAKE_CXX_STANDARD 17)
9+
set(CMAKE_CXX_STANDARD_REQUIRED ON)
10+
11+
# Library configuration
12+
add_library(json_parser STATIC
13+
json_parser.h
14+
json_parser.c
15+
)
16+
17+
set_target_properties(json_parser PROPERTIES
18+
C_VISIBILITY_PRESET hidden
19+
INTERPROCEDURAL_OPTIMIZATION FALSE
20+
)
21+
22+
target_include_directories(json_parser PUBLIC
23+
${CMAKE_CURRENT_SOURCE_DIR}
24+
)
25+
26+
# C demo
27+
add_executable(demo
28+
demo.c
29+
)
30+
31+
# C++17 demo
32+
add_executable(demo_cpp
33+
demo.cpp
34+
)
35+
36+
# Link demo to library
37+
target_link_libraries(demo PRIVATE json_parser)
38+
target_link_libraries(demo_cpp PRIVATE json_parser)
39+
40+
# Google Test configuration
41+
find_package(GTest REQUIRED)
42+
find_package(Threads REQUIRED)
43+
44+
# Test executable
45+
add_executable(json_parser_tests
46+
json_parser_test.cpp
47+
)
48+
49+
target_link_libraries(json_parser_tests
50+
PRIVATE
51+
json_parser
52+
GTest::GTest
53+
GTest::Main
54+
Threads::Threads
55+
)
56+
57+
enable_testing()
58+
add_test(NAME json_parser_tests COMMAND json_parser_tests)
59+
60+
# Installation configuration
61+
install(TARGETS json_parser
62+
ARCHIVE DESTINATION lib
63+
LIBRARY DESTINATION lib
64+
INCLUDES DESTINATION include
65+
)
66+
67+
install(FILES json_parser.h
68+
DESTINATION include
69+
)

README.md

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,45 @@
1-
# json_parser
2-
Header only lightweight JSON parser library
1+
# JSON Parser Library
2+
3+
A lightweight, single-header C library for parsing JSON data. Designed for simplicity and portability, this parser provides a low-footprint solution to decode JSON-formatted strings into structured tokens while adhering to core JSON specifications.
4+
5+
## Features
6+
7+
- **Standard Compliance**: Supports parsing of JSON objects, arrays, strings, numbers, and literals (`true`, `false`, `null`).
8+
- **Unicode Support**: Handles UTF-16 surrogate pairs and encodes Unicode escape sequences into valid UTF-8.
9+
- **Configurable Limits**: Tunable thresholds for maximum nesting depth, token count, and string length.
10+
- **Error Reporting**: Detailed error codes and human-readable error messages for troubleshooting parsing issues.
11+
- **Memory Safety**: Cleanup functions ensure allocated resources are properly released.
12+
13+
## Components
14+
15+
### Core Structures
16+
- **`json_parser_t`**: Manages the parser state, including input data, token storage, and error tracking.
17+
- **`json_token_t`**: Represents a parsed JSON token, storing its type (object, array, string, number, etc.) and associated value.
18+
- **`json_error_t`**: Enumerates all possible parsing errors, such as invalid tokens, nesting depth exceeded, or allocation failures.
19+
20+
### Key Functions
21+
- **Initialization & Cleanup**: `json_parser_init` prepares the parser, while `json_parser_free` releases allocated memory.
22+
- **Parsing**: `json_parser_parse` processes the input JSON string and populates tokens.
23+
- **Utilities**: `json_get_tokens` retrieves parsed tokens, and `json_error_string` converts error codes to descriptive messages.
24+
25+
## Error Handling
26+
The parser tracks errors during execution and halts on the first encountered issue. Errors range from syntax violations (e.g., unexpected characters) to resource constraints (e.g., exceeding token limits). Users can programmatically check the error type and respond accordingly.
27+
28+
## Building
29+
The library is implemented as a single-header file (`json_parser.h`) with optional embedded implementation. It can be integrated into projects in two ways:
30+
1. **As a Header-Only Library**: Define `JSON_PARSER_IMPLEMENTATION` in one source file to include the implementation.
31+
2. **As a Static Library**: Use the provided CMake configuration to compile a static library, simplifying linking in larger projects.
32+
33+
## Usage
34+
1. **Initialize the Parser**: Provide the JSON input string and its length.
35+
2. **Parse the Input**: Execute the parsing routine and check for errors.
36+
3. **Retrieve Tokens**: Access the parsed tokens to read JSON structure and values.
37+
4. **Cleanup**: Release parser resources after processing.
38+
39+
## :snowman: Author
40+
41+
Eray Öztürk ([@diffstorm](https://github.com/diffstorm))
42+
43+
## License
44+
45+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

demo.c

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
@brief JSON Parser Library
3+
4+
A lightweight, single-header C library for parsing JSON data. Designed for simplicity and portability, this parser provides a low-footprint solution to decode JSON-formatted strings into structured tokens while adhering to core JSON specifications.
5+
6+
@date 2025-05-03
7+
@version 1.0
8+
@author Eray Ozturk | erayozturk1@gmail.com
9+
@url github.com/diffstorm
10+
@license MIT License
11+
*/
12+
13+
#include <stdio.h>
14+
#include <string.h>
15+
#define JSON_PARSER_IMPLEMENTATION
16+
#include "json_parser.h"
17+
18+
int main() {
19+
const char *json = "{\"name\":\"John\\u00D0e\",\"age\":30,\"scores\":[90.5,80.0]}";
20+
json_parser_t parser;
21+
json_parser_init(&parser, json, strlen(json));
22+
23+
json_error_t error = json_parser_parse(&parser);
24+
if (error != JSON_ERROR_NONE) {
25+
printf("Error: %s\n", json_error_string(error));
26+
return 1;
27+
}
28+
29+
size_t count;
30+
const json_token_t *tokens = json_get_tokens(&parser, &count);
31+
for (size_t i = 0; i < count; i++) {
32+
const json_token_t *t = &tokens[i];
33+
printf("Token %zu: ", i);
34+
switch (t->type) {
35+
case JSON_TOKEN_OBJECT:
36+
printf("Object\n"); break;
37+
case JSON_TOKEN_ARRAY:
38+
printf("Array\n"); break;
39+
case JSON_TOKEN_STRING:
40+
printf("String: %s\n", t->value.string); break;
41+
case JSON_TOKEN_NUMBER:
42+
printf("Number: %f\n", t->value.number); break;
43+
case JSON_TOKEN_TRUE:
44+
printf("Boolean: true\n"); break;
45+
case JSON_TOKEN_FALSE:
46+
printf("Boolean: false\n"); break;
47+
case JSON_TOKEN_NULL:
48+
printf("Null\n"); break;
49+
default:
50+
printf("Unknown\n");
51+
}
52+
}
53+
54+
json_parser_free(&parser);
55+
return 0;
56+
}

demo.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
@brief JSON Parser Library
3+
4+
A lightweight, single-header C library for parsing JSON data. Designed for simplicity and portability, this parser provides a low-footprint solution to decode JSON-formatted strings into structured tokens while adhering to core JSON specifications.
5+
6+
@date 2025-05-03
7+
@version 1.0
8+
@author Eray Ozturk | erayozturk1@gmail.com
9+
@url github.com/diffstorm
10+
@license MIT License
11+
*/
12+
13+
#include <iostream>
14+
#include <string>
15+
16+
#include "json_parser.h"
17+
18+
int main() {
19+
// Use raw string literal to avoid escaping characters
20+
const std::string json = R"({"name":"John\u00D0e","age":30,"scores":[90.5,80.0]})";
21+
22+
json_parser_t parser;
23+
json_parser_init(&parser, json.data(), json.size());
24+
25+
const json_error_t error = json_parser_parse(&parser);
26+
if (error != JSON_ERROR_NONE) {
27+
std::cerr << "Error: " << json_error_string(error) << "\n";
28+
json_parser_free(&parser);
29+
return 1;
30+
}
31+
32+
size_t token_count = 0;
33+
const json_token_t* tokens = json_get_tokens(&parser, &token_count);
34+
35+
for (size_t i = 0; i < token_count; ++i) {
36+
const auto& token = tokens[i];
37+
std::cout << "Token " << i << ": ";
38+
39+
switch (token.type) {
40+
case JSON_TOKEN_OBJECT:
41+
std::cout << "Object\n";
42+
break;
43+
case JSON_TOKEN_ARRAY:
44+
std::cout << "Array\n";
45+
break;
46+
case JSON_TOKEN_STRING:
47+
std::cout << "String: " << token.value.string << "\n";
48+
break;
49+
case JSON_TOKEN_NUMBER:
50+
std::cout << "Number: " << token.value.number << "\n";
51+
break;
52+
case JSON_TOKEN_TRUE:
53+
std::cout << "Boolean: true\n";
54+
break;
55+
case JSON_TOKEN_FALSE:
56+
std::cout << "Boolean: false\n";
57+
break;
58+
case JSON_TOKEN_NULL:
59+
std::cout << "Null\n";
60+
break;
61+
default:
62+
std::cout << "Unknown\n";
63+
}
64+
}
65+
66+
json_parser_free(&parser);
67+
return 0;
68+
}

json_parser.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
@brief JSON Parser Library
3+
4+
A lightweight, single-header C library for parsing JSON data. Designed for simplicity and portability, this parser provides a low-footprint solution to decode JSON-formatted strings into structured tokens while adhering to core JSON specifications.
5+
6+
@date 2025-05-03
7+
@version 1.0
8+
@author Eray Ozturk | erayozturk1@gmail.com
9+
@url github.com/diffstorm
10+
@license MIT License
11+
*/
12+
13+
#define JSON_PARSER_IMPLEMENTATION
14+
#include "json_parser.h"

0 commit comments

Comments
 (0)