### Conditional Build for Installation Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_validate/CMakeLists.txt Conditionally builds the pbnjson_validate program for installation if PBNJSON_INSTALL_TOOLS is enabled. ```cmake if (PBNJSON_INSTALL_TOOLS) webos_build_program(NAME pbnjson_validate) endif () ``` -------------------------------- ### Schema Validation with jschema_create and jvalue_validate Source: https://context7.com/webosose/libpbnjson/llms.txt Demonstrates how to create a compiled JSON schema from a string and validate a JSON DOM value against it. Includes examples for both valid and invalid payloads. ```APIDOC ## Schema Validation — `jschema_create` / `jvalue_validate` Creates a compiled schema from an inline JSON Schema string and validates a DOM value against it. `jvalue_validate_apply` additionally fills in schema-specified default values. ```c #include #include int main(void) { const char *schema_str = "{" " \"type\": \"object\",\n" " \"properties\": {\n" " \"name\": { \"type\": \"string\" },\n" " \"age\": { \"type\": \"integer\", \"minimum\": 0 }\n" " },\n" " \"required\": [\"name\", \"age\"]\n" "}"; jerror *serr = NULL; jschema_ref schema = jschema_create(j_cstr_to_buffer(schema_str), &serr); if (!schema) { fprintf(stderr, "Bad schema: %s\n", jerror_message(serr)); jerror_free(serr); return 1; } // Valid payload jerror *verr = NULL; jvalue_ref good = jdom_create( j_cstr_to_buffer("{\"name\":\"Carol\",\"age\":28}"), jschema_all(), NULL); bool ok = jvalue_validate(good, schema, &verr); printf("valid: %s\n", ok ? "true" : "false"); // Output: valid: true j_release(&good); // Invalid payload (age is a string) jvalue_ref bad = jdom_create( j_cstr_to_buffer("{\"name\":\"Dave\",\"age\":\"old\"}"), jschema_all(), NULL); ok = jvalue_validate(bad, schema, &verr); printf("valid: %s\n", ok ? "true" : "false"); if (!ok) { fprintf(stderr, "Error: %s\n", jerror_message(verr)); jerror_free(verr); } // Output: valid: false j_release(&bad); jschema_release(&schema); return 0; } ``` ``` -------------------------------- ### C++ API: Building Objects with JObject and Initializer Lists Source: https://context7.com/webosose/libpbnjson/llms.txt Illustrates how to construct `JObject` and `JArray` instances using C++11 initializer lists and `JValue::KeyValue` pairs for concise inline JSON creation. ```APIDOC ### Building Objects with `JObject` and Initializer Lists (C++11) `JObject` and `JArray` can be constructed from C++11 initializer lists using `JValue::KeyValue` pairs, allowing terse inline construction of arbitrarily nested structures. ```cpp #include #include int main() { using namespace pbnjson; JValue config = JObject { { "server", JObject { { "host", "0.0.0.0" }, { "port", 443 } }}, { "debug", false }, { "tags", JArray { "production", "v2", "stable" } } }; // Traverse nested structure std::string host; config["server"]["host"].asString(host); std::cout << "host: " << host << "\n"; // Output: host: 0.0.0.0 int32_t port = 0; config["server"]["port"].asNumber(port); std::cout << "port: " << port << "\n"; // Output: port: 443 std::cout << "tags size: " << config["tags"].arraySize() << "\n"; // Output: tags size: 3 // Serialize with pretty-print std::cout << config.stringify(" ") << "\n"; return 0; } ``` ``` -------------------------------- ### Build Library and Pkgconfig Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Invokes custom build commands for creating the library and its pkgconfig file. ```cmake webos_build_library(NAME pbnjson_c${CLANG_EXT}) webos_build_pkgconfig(files/pkgconfig/pbnjson_c) ``` -------------------------------- ### Configure C++ Compiler Flags and Includes Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/test/CMakeLists.txt Sets C++ standard to C++0x, enables all warnings, and includes the webOS Google Test headers. ```cmake set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -Wall") include_directories(${WEBOS_GTEST_INCLUDES}) ``` -------------------------------- ### Loading Schema and JSON Document from Files in C++ Source: https://context7.com/webosose/libpbnjson/llms.txt Illustrates loading a JSON schema from a file using `JSchema::fromFile()` and parsing/validating a JSON document from another file using `JDomParser::fromFile()`, which is common in webOS service integrations. ```cpp #include #include int main() { using namespace pbnjson; // Load and compile schema from disk JSchema schema = JSchema::fromFile("/usr/share/myapp/schema/request.json"); if (!schema) { std::cerr << "Cannot load schema\n"; return 1; } // Parse and validate a JSON file against the schema JValue doc = JDomParser::fromFile("/tmp/request.json", schema); if (!doc.isValid()) { std::cerr << "Document invalid or schema violation\n"; return 1; } std::cout << "Loaded: " << doc.stringify() << "\n"; return 0; } ``` -------------------------------- ### Include Directories Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Sets up include directories for the project. This ensures that header files are found during compilation. ```cmake include_directories( ${API_HEADERS} ${API_HEADERS}/pbnjson ${API_HEADERS}/pbnjson/c ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) ``` -------------------------------- ### Define Unit Tests and Build Executables Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/selectors/test/CMakeLists.txt Lists all unit test targets and iterates through them to create executables. Each executable is built from its corresponding .cpp file and Utils.cpp, then linked against pbnjson_cpp, webOS Google Test libraries, and GLib2. ```cmake SET(UnitTests TestSyntaxParser TestChildrenGenerators TestSimpleSelectors TestTypeSelectors TestKeySelectors TestContainsSelector TestHas TestExpression TestParentCombinator TestAncestorCombinator TestSiblingCombinator TestArrayElements TestValueSelector TestOrSelector ) FOREACH(TEST ${UnitTests}) add_executable(${TEST} ${TEST}.cpp Utils.cpp) target_link_libraries(${TEST} ${TEST_LIBRARIES} ${WEBOS_GTEST_LIBRARIES} ${GLIB2_LDFLAGS}) add_test(Selectors.${TEST} ${TEST}) ENDFOREACH() ``` -------------------------------- ### Generate Schema Keywords and Instance Types Headers Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Uses the 'gperf_generate' function to create 'schema_keywords.h' and 'instance_types.h' from their respective .gperf input files. These headers are likely used for efficient lookups. ```cmake gperf_generate(schema_keywords.gperf schema_keywords.h) gperf_generate(instance_types.gperf instance_types.h) ``` -------------------------------- ### Add Executable and Link Libraries Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_validate/CMakeLists.txt Defines the pbnjson_validate executable and links it with the pbnjson_cpp library and Boost program_options. ```cmake add_executable(pbnjson_validate pbnjson_validate.cpp) target_link_libraries(pbnjson_validate pbnjson_cpp ${Boost_PROGRAM_OPTIONS_LIBRARIES}) ``` -------------------------------- ### Define and Build Unit Tests Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/test/CMakeLists.txt Defines a list of unit test executables and then iterates through them to add them as executables, link necessary libraries, and register them as tests. ```cmake SET(UnitTests TestValidator TestValidatorEquals TestGenericValidator TestNullValidator TestBooleanValidator TestNumber TestNumberValidator TestIntegerValidator TestStringValidator TestArrayValidator TestObjectValidator TestCombinedTypesValidator TestAllOfValidator TestAnyOfValidator TestOneOfValidator TestNotValidator TestParser TestJson TestUriScope TestUriResolver TestDefinitions TestReference TestArrayValidator2 TestEnum TestMetaSchema ) FOREACH(TEST ${UnitTests}) add_executable(${TEST} ${TEST}.cpp) target_link_libraries(${TEST} schema_validation ${WEBOS_GTEST_LIBRARIES} ${GLIB2_LDFLAGS}) add_test(Validation.${TEST} ${TEST}) ENDFOREACH() ``` -------------------------------- ### Custom Command to Generate Schema Grammar C File Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Generates 'json_schema_grammar.c' and 'json_schema_grammar.h' from 'json_schema_grammar.y' using the 'apply_lemon.sh' script. This command is executed when the 'json_schema_grammar' target is built. ```cmake add_custom_command( SOURCE json_schema_grammar.y COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/apply_lemon.sh ${LEMON} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} json_schema_grammar.y TARGET json_schema_grammar OUTPUTS ${CMAKE_CURRENT_BINARY_DIR}/json_schema_grammar.c ${CMAKE_CURRENT_BINARY_DIR}/json_schema_grammar.h DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/json_schema_grammar.y ${CMAKE_CURRENT_SOURCE_DIR}/apply_lemon.sh ) ``` -------------------------------- ### Build JSON Objects with C++11 Initializer Lists Source: https://context7.com/webosose/libpbnjson/llms.txt Constructs JObject and JArray using C++11 initializer lists and JValue::KeyValue pairs for terse inline JSON construction. ```cpp #include #include int main() { using namespace pbnjson; JValue config = JObject { { "server", JObject { { "host", "0.0.0.0" }, { "port", 443 } }}, { "debug", false }, { "tags", JArray { "production", "v2", "stable" } } }; // Traverse nested structure std::string host; config["server"]["host"].asString(host); std::cout << "host: " << host << "\n"; // Output: host: 0.0.0.0 int32_t port = 0; config["server"]["port"].asNumber(port); std::cout << "port: " << port << "\n"; // Output: port: 443 std::cout << "tags size: " << config["tags"].arraySize() << "\n"; // Output: tags size: 3 // Serialize with pretty-print std::cout << config.stringify(" ") << "\n"; return 0; } ``` -------------------------------- ### Build Shared Library 'pbnjson_c' Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Defines and builds the shared library 'pbnjson_c'. This is the main library target, potentially with a CLANG suffix. ```cmake add_library( pbnjson_c${CLANG_EXT} SHARED jgen_stream.c jvalue_tostring.c jparse_stream.c jschema.c jschema_jvalue.c jvalidation.c jtraverse.c parser_memory_pool.c $ ) target_link_libraries( pbnjson_c${CLANG_EXT} jvalue schema_validation ${GLIB2_LDFLAGS} ${YAJL_LDFLAGS} ${CMAKE_THREAD_LIBS_INIT} ) if(UNIX) target_link_libraries(pbnjson_c${CLANG_EXT} m) endif() set_target_properties(pbnjson_c${CLANG_EXT} PROPERTIES DEFINE_SYMBOL PJSON_SHARED) ``` -------------------------------- ### Build Subdirectories Source: https://github.com/webosose/libpbnjson/blob/master/src/CMakeLists.txt Includes subdirectories for building the C, C++, and validation components of the library. ```cmake add_subdirectory(pbnjson_c) add_subdirectory(pbnjson_cxx) add_subdirectory(pbnjson_validate) ``` -------------------------------- ### Enable Testing Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Enables the testing framework if the build option for tests is set. ```cmake if(WEBOS_CONFIG_BUILD_TESTS) enable_testing() endif() ``` -------------------------------- ### Set C++ Compiler Flags and Include Directories Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/selectors/test/CMakeLists.txt Configures C++ compiler flags to C++11 standard and enables all warnings. It also includes the webOS Google Test include directories. ```cmake set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall") include_directories(${WEBOS_GTEST_INCLUDES}) ``` -------------------------------- ### Define Test Libraries Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/selectors/test/CMakeLists.txt Specifies the primary library for the tests, which is 'pbnjson_cpp'. ```cmake set(TEST_LIBRARIES pbnjson_cpp) ``` -------------------------------- ### Building JSON Objects with jobject_create_var and jobject_put Source: https://context7.com/webosose/libpbnjson/llms.txt Constructs JSON objects dynamically. `jobject_create_var` takes a variable argument list of key-value pairs. `jobject_put` adds new key-value pairs, transferring ownership of the value. ```c #include #include int main(void) { // Build nested object using create_var (ownership of values transferred) jvalue_ref addr = jobject_create_var( jkeyval(J_CSTR_TO_JVAL("street"), jstring_create("123 Main St")), jkeyval(J_CSTR_TO_JVAL("zip"), jstring_create("90210")), J_END_OBJ_DECL ); jvalue_ref person = jobject_create_var( jkeyval(J_CSTR_TO_JVAL("name"), jstring_create("Bob")), jkeyval(J_CSTR_TO_JVAL("age"), jnumber_create_i32(25)), jkeyval(J_CSTR_TO_JVAL("address"), addr), // addr ownership transferred J_END_OBJ_DECL ); // Add another key dynamically (put transfers ownership) jobject_put(person, J_CSTR_TO_JVAL("active"), jboolean_true()); printf("%s\n", jvalue_stringify(person)); // Output: {"name":"Bob","age":25,"address":{"street":"123 Main St","zip":"90210"},"active":true} // Lookup with key existence check jvalue_ref zip_ref; if (jobject_get_exists(addr, J_CSTR_TO_BUF("zip"), &zip_ref)) { // addr was transferred — use person path instead } jvalue_ref street = jobject_get( jobject_get(person, J_CSTR_TO_BUF("address")), J_CSTR_TO_BUF("street") ); raw_buffer s = jstring_get_fast(street); printf("street: %.*s\n", (int)s.m_len, s.m_str); // Output: street: 123 Main St j_release(&person); return 0; } ``` -------------------------------- ### Serialization with jvalue_stringify and jvalue_prettify Source: https://context7.com/webosose/libpbnjson/llms.txt Shows how to convert a JSON DOM tree back into a compact or pretty-printed JSON string using `jvalue_stringify` and `jvalue_prettify`. ```APIDOC ## Serialization — `jvalue_stringify` / `jvalue_prettify` Converts a DOM tree back to a compact or pretty-printed JSON string. The returned pointer is valid for the lifetime of the `jvalue_ref` (or until the value is modified). ```c #include #include int main(void) { jvalue_ref obj = jobject_create_var( jkeyval(J_CSTR_TO_JVAL("host"), jstring_create("localhost")), jkeyval(J_CSTR_TO_JVAL("port"), jnumber_create_i32(8080)), J_END_OBJ_DECL ); // Compact printf("compact: %s\n", jvalue_stringify(obj)); // Output: compact: {"host":"localhost","port":8080} // Pretty-printed with 2-space indent printf("pretty:\n%s\n", jvalue_prettify(obj, " ")); // Output: // pretty: // { // "host": "localhost", // "port": 8080 // } j_release(&obj); return 0; } ``` ``` -------------------------------- ### Building JSON Objects Source: https://context7.com/webosose/libpbnjson/llms.txt This section covers constructing JSON object DOM nodes using `jobject_create_var`, `jobject_put`, and `jobject_get`. `jobject_create_var` accepts a variable argument list of `jkeyval()` pairs, `jobject_put` transfers ownership of a value into the object, and `jobject_get` retrieves a borrowed reference. ```APIDOC ## Building JSON Objects — `jobject_create_var` / `jobject_put` / `jobject_get` Constructs a JSON object DOM node. `jobject_create_var` takes a variable argument list of `jkeyval()` pairs terminated with `J_END_OBJ_DECL`. `jobject_put` transfers ownership of a value into the object; `jobject_get` retrieves a borrowed reference. ```c #include #include int main(void) { // Build nested object using create_var (ownership of values transferred) jvalue_ref addr = jobject_create_var( jkeyval(J_CSTR_TO_JVAL("street"), jstring_create("123 Main St")), jkeyval(J_CSTR_TO_JVAL("zip"), jstring_create("90210")), J_END_OBJ_DECL ); jvalue_ref person = jobject_create_var( jkeyval(J_CSTR_TO_JVAL("name"), jstring_create("Bob")), jkeyval(J_CSTR_TO_JVAL("age"), jnumber_create_i32(25)}, jkeyval(J_CSTR_TO_JVAL("address"), addr), // addr ownership transferred J_END_OBJ_DECL ); // Add another key dynamically (put transfers ownership) jobject_put(person, J_CSTR_TO_JVAL("active"), jboolean_true()); printf("%s\n", jvalue_stringify(person)); // Output: {"name":"Bob","age":25,"address":{"street":"123 Main St","zip":"90210"},"active":true} // Lookup with key existence check jvalue_ref zip_ref; if (jobject_get_exists(addr, J_CSTR_TO_BUF("zip"), &zip_ref)) { // addr was transferred — use person path instead } jvalue_ref street = jobject_get( jobject_get(person, J_CSTR_TO_BUF("address")), J_CSTR_TO_BUF("street") ); raw_buffer s = jstring_get_fast(street); printf("street: %.*s\n", (int)s.m_len, s.m_str); // Output: street: 123 Main St j_release(&person); return 0; } ``` ``` -------------------------------- ### Iterating JSON Arrays and Objects in C++ Source: https://context7.com/webosose/libpbnjson/llms.txt Demonstrates how to iterate over elements in a JSON array and key-value pairs in a JSON object using C++11 range-based for loops with `JValue::items()` and `JValue::children()`. ```cpp #include #include int main() { using namespace pbnjson; JValue arr = JDomParser::fromString(R"([10, 20, 30, 40])"); // Array iteration int64_t sum = 0; for (const JValue &elem : arr.items()) { int64_t n = 0; elem.asNumber(n); sum += n; } std::cout << "sum: " << sum << "\n"; // Output: sum: 100 JValue obj = JDomParser::fromString(R"({\"x\":1,\"y\":2,\"z\":3})"); // Object iteration for (const JValue::KeyValue &kv : obj.children()) { std::string key; int32_t val = 0; kv.first.asString(key); kv.second.asNumber(val); std::cout << key << " -> " << val << "\n"; } // Output: // x -> 1 // y -> 2 // z -> 3 return 0; } ``` -------------------------------- ### Copy Schema Files for Testing Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/test/CMakeLists.txt Finds all schema files recursively and copies them to the build directory to be accessible during testing. ```cmake file(GLOB_RECURSE SCHEMAS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} schemas/*) foreach(schema ${SCHEMAS}) configure_file(${schema} ${schema} COPYONLY) endforeach() ``` -------------------------------- ### C++ API: Parsing with JDomParser::fromString Source: https://context7.com/webosose/libpbnjson/llms.txt Demonstrates parsing a JSON string into a `JValue` object using the static `JDomParser::fromString` method in the `pbnjson` namespace. Shows basic type checking and value extraction. ```APIDOC ## C++ API (`pbnjson` namespace) ### Parsing with `JDomParser::fromString` Static convenience method that parses a JSON string and returns a `JValue`. Uses `JSchema::AllSchema()` by default; pass a `JSchema` to validate during parsing. ```cpp #include #include int main() { using namespace pbnjson; // Parse with the permissive schema JValue v = JDomParser::fromString(R"({\"city\":\"Berlin\",\"pop\":3700000})"); if (!v.isValid()) { std::cerr << "Parse failed\n"; return 1; } std::string city; v["city"].asString(city); std::cout << "City: " << city << "\n"; // Output: City: Berlin int64_t pop = 0; v["pop"].asNumber(pop); std::cout << "Pop: " << pop << "\n"; // Output: Pop: 3700000 // Type queries std::cout << std::boolalpha << "isObject: " << v.isObject() << "\n" << "hasKey pop: " << v.hasKey("pop") << "\n"; return 0; } ``` ``` -------------------------------- ### Configure Header Files Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Configures specific header files for system compatibility. These generated headers provide definitions based on system checks. ```cmake configure_file(${CMAKE_CURRENT_SOURCE_DIR}/sys_malloc.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/sys_malloc.h) ``` ```cmake configure_file(${CMAKE_CURRENT_SOURCE_DIR}/pjson_syslog.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/pjson_syslog.h) ``` ```cmake configure_file(${CMAKE_CURRENT_SOURCE_DIR}/strnlen.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/strnlen.h) ``` ```cmake configure_file(${CMAKE_CURRENT_SOURCE_DIR}/isatty.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/isatty.h) ``` -------------------------------- ### Building and Accessing JSON Arrays Source: https://context7.com/webosose/libpbnjson/llms.txt This section details how to create JSON array nodes and access elements by index using `jarray_create`, `jarray_append`, and `jarray_get`. `jarray_append` transfers ownership of the appended value to the array. ```APIDOC ## Building and Accessing JSON Arrays — `jarray_create` / `jarray_append` / `jarray_get` Creates an array node and provides element access by index. `jarray_append` transfers ownership of the appended value to the array. ```c #include #include int main(void) { jvalue_ref arr = jarray_create(NULL); jarray_append(arr, jstring_create("hello")); jarray_append(arr, jnumber_create_f64(3.14)); jarray_append(arr, jboolean_false()); jarray_append(arr, jnull()); ssize_t sz = jarray_size(arr); printf("size: %zd\n", sz); // Output: size: 4 for (ssize_t i = 0; i < sz; i++) { jvalue_ref elem = jarray_get(arr, i); printf("[%zd] type=%d raw=%s\n", i, jget_type(elem), jvalue_stringify(elem)); } // Output: // [0] type=... raw="hello" // [1] type=... raw=3.14 // [2] type=... raw=false // [3] type=... raw=null j_release(&arr); return 0; } ``` ``` -------------------------------- ### JSON Schema Validation and Default Value Application in C++ Source: https://context7.com/webosose/libpbnjson/llms.txt Shows how to compile a JSON schema from a string, validate a JSON object against it using `JSchema::validate()`, and apply default values defined in the schema using `JSchema::apply()`. ```cpp #include #include int main() { using namespace pbnjson; JSchema schema = JSchema::fromString(R"({ \"type\": \"object\", \"properties\": { \"username\": { \"type\": \"string\", \"minLength\": 3 }, \"score\": { \"type\": \"number\", \"minimum\": 0 }, \"role\": { \"type\": \"string\", \"default\": \"user\" } }, \"required\": [\"username\", \"score\"] })"); if (!schema) { std::cerr << "Invalid schema\n"; return 1; } // Valid object — apply also inserts "role" default JValue obj = JDomParser::fromString(R"({\"username\":\"alice\",\"score\":99})"); JResult result = schema.apply(obj); if (!result) { std::cerr << "Validation failed: " << result.errorString() << "\n"; return 1; } // "role" default was inserted by apply() std::string role; obj["role"].asString(role); std::cout << "role after apply: " << role << "\n"; // Output: role after apply: user // Invalid object — score is a string JValue bad = JDomParser::fromString(R"({\"username\":\"bob\",\"score\":\"high\"})"); JResult bad_result = schema.validate(bad); std::cout << "bad valid: " << std::boolalpha << (bool)bad_result << "\n"; // Output: bad valid: false std::cout << "error: " << bad_result.errorString() << "\n"; return 0; } ``` -------------------------------- ### Add Linker Options Source: https://github.com/webosose/libpbnjson/blob/master/src/CMakeLists.txt Sets linker options to disallow undefined symbols, ensuring all symbols are resolved during the linking stage. ```cmake webos_add_linker_options(ALL --no-undefined) ``` -------------------------------- ### Serializing JSON to String in C++ Source: https://context7.com/webosose/libpbnjson/llms.txt Demonstrates serializing a `JValue` object into a `std::string` using `JValue::stringify()`. An optional argument can be provided for pretty-printing with indentation. ```cpp #include #include int main() { using namespace pbnjson; JValue resp = JObject { { "status", "ok" }, { "code", 200 }, { "data", JArray { 1, 2, 3 } } }; // Compact std::cout << resp.stringify() << "\n"; // Output: {"status":"ok","code":200,"data":[1,2,3]} // Pretty-printed with tab indent std::cout << resp.stringify("\t") << "\n"; // Output: // { // "status": "ok", // "code": 200, // "data": [ // 1, // 2, // 3 // ] // } return 0; } ``` -------------------------------- ### Add Schema Validation Library Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Defines the static library 'schema_validation' and lists all its source files, including generated headers and various C files implementing validation logic. ```cmake add_library( schema_validation STATIC ${CMAKE_CURRENT_BINARY_DIR}/schema_keywords.h ${CMAKE_CURRENT_BINARY_DIR}/instance_types.h ${grammar_c} additional_feature.c array_items.c array_validator.c boolean_feature.c boolean_validator.c count_feature.c definitions.c error_code.c everything_validator.c feature.c generic_validator.c jvalue_feature.c nothing_validator.c null_validator.c number.c number_feature.c number_validator.c string_validator.c object_pattern_properties.c object_properties.c object_required.c object_validator.c combined_types_validator.c combined_validator.c parser_api.c parser_context.c pattern.c reference.c schema_builder.c schema_parsing.c type_parser.c uri_scope.c uri_resolver.c validation_api.c validation_event.c validation_state.c validator.c ) ``` -------------------------------- ### Build Static Library 'jvalue' Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Defines and builds the static library 'jvalue'. This library contains core JSON value manipulation functions. ```cmake add_library( jvalue STATIC debugging.c jobject.c jerror.c jvalue/num_conversion.c key_dictionary.c dom_string_memory_pool.c ) set_target_properties(jvalue PROPERTIES DEFINE_SYMBOL PJSON_SHARED) ``` -------------------------------- ### Iterating Object Keys Source: https://context7.com/webosose/libpbnjson/llms.txt This section explains how to traverse all key-value pairs of a JSON object using a stack-allocated iterator with `jobject_iter_init` and `jobject_iter_next`. The iterator borrows ownership from the parent object, which must remain alive during iteration. ```APIDOC ## Iterating Object Keys — `jobject_iter_init` / `jobject_iter_next` Stack-allocated iterator for traversing all key-value pairs of a JSON object. The iterator borrows ownership from the parent; the parent must remain alive throughout iteration. ```c #include #include int main(void) { const char *json = "{\"a\":1,\"b\":2,\"c\":3}"; jerror *err = NULL; jvalue_ref obj = jdom_create(j_cstr_to_buffer(json), jschema_all(), &err); jobject_iter it; jobject_key_value kv; jobject_iter_init(&it, obj); while (jobject_iter_next(&it, &kv)) { raw_buffer key = jstring_get_fast(kv.key); int32_t val = 0; jnumber_get_i32(kv.value, &val); printf("%.*s = %d\n", (int)key.m_len, key.m_str, val); } // Output: // a = 1 // b = 2 // c = 3 j_release(&obj); return 0; } ``` ``` -------------------------------- ### Building and Accessing JSON Arrays with jarray_create and jarray_append Source: https://context7.com/webosose/libpbnjson/llms.txt Creates JSON array nodes and allows appending values. `jarray_append` transfers ownership of the appended value to the array. Element access is provided by index. ```c #include #include int main(void) { jvalue_ref arr = jarray_create(NULL); jarray_append(arr, jstring_create("hello")); jarray_append(arr, jnumber_create_f64(3.14)); jarray_append(arr, jboolean_false()); jarray_append(arr, jnull()); ssize_t sz = jarray_size(arr); printf("size: %zd\n", sz); // Output: size: 4 for (ssize_t i = 0; i < sz; i++) { jvalue_ref elem = jarray_get(arr, i); printf("[%zd] type=%d raw=%s\n", i, jget_type(elem), jvalue_stringify(elem)); } // Output: // [0] type=... raw="hello" // [1] type=... raw=3.14 // [2] type=... raw=false // [3] type=... raw=null j_release(&arr); return 0; } ``` -------------------------------- ### Configure GCC/Clang Compiler Flags Source: https://github.com/webosose/libpbnjson/blob/master/src/CMakeLists.txt Applies specific compiler flags for GCC and Clang, including warnings, optimization levels, and debug definitions based on the build type. ```cmake if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) # fmessage-length=0: Make sure that errors & messages are printed on 1 line webos_add_compiler_flags(ALL -fmessage-length=0 -Wall) webos_add_compiler_flags(DEBUG -O0 -DDEBUG -D_DEBUG -DPJSON_LOG_INFO -DPJSON_LOG_STDOUT) webos_add_compiler_flags(RELEASE -DNDEBUG -g) else() # don't take out this message - this is the default fall-through case when the # compiler cannot be determined. instead, add compiler detection as necessary message("WARNING - not using GCC for compilation - please provide flags to enable C99") webos_add_compiler_flags(ALL -D_BSD_SOURCE) endif() ``` -------------------------------- ### Include Directories for Schema Validation Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Configures include directories for the schema validation build. This ensures that header files from various locations, including the build and source directories, are accessible. ```cmake include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/.. ${CMAKE_CURRENT_SOURCE_DIR}/.. ${API_HEADERS} ${API_HEADERS}/pbnjson ${API_HEADERS}/pbnjson/c ) ``` -------------------------------- ### Conditional Definitions Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Adds preprocessor definitions based on build options. These control logging verbosity and tracing levels. ```cmake if(WITH_VERBOSE_DEBUG) add_definitions(-DPJSON_LOG_DBG=1) endif() if(WITH_VERBOSE_TRACE) add_definitions(-DPJSON_LOG_TRACE=1) add_definitions(-DPJSON_SCHEMA_TRACE=3) endif() add_definitions(-DLIBRARY_NAME=pbnjson_c${CLANG_EXT}) add_definitions(-DPJSON_EXPORT) ``` -------------------------------- ### Parsing JSON from a File - jdom_fcreate Source: https://context7.com/webosose/libpbnjson/llms.txt Reads and parses a JSON document directly from a file path, validating it against a provided schema. Returns an owned jvalue_ref; errors are reported through the jerror ** output parameter. ```APIDOC ## jdom_fcreate ### Description Reads and parses a JSON document directly from a file path, validating it against a provided schema. Returns an owned `jvalue_ref`; errors are reported through the `jerror **` output parameter. ### Method `jdom_fcreate` ### Parameters - `path` (const char*): The file path to the JSON document. - `schema` (jvalue_ref): The JSON schema to validate against (e.g., `jschema_all()` for any valid JSON). - `err` (jerror **): Pointer to a jerror pointer to store error information. ### Return Value - `jvalue_ref`: A reference to the parsed JSON DOM tree, or `jinvalid()` on failure. ### Request Example ```c #include #include int main(void) { jerror *err = NULL; jvalue_ref root = jdom_fcreate("/etc/config/settings.json", jschema_all(), &err); if (!jis_valid(root)) { fprintf(stderr, "Failed to load file: %s\n", jerror_message(err)); jerror_free(err); return 1; } printf("JSON: %s\n", jvalue_stringify(root)); j_release(&root); return 0; } ``` ### Response #### Success Response - `jvalue_ref`: A valid `jvalue_ref` representing the JSON DOM. #### Error Response - `jinvalid()`: If file reading or parsing fails. Error details are available via the `jerror` pointer. ``` -------------------------------- ### DOM Stream Parsing Source: https://context7.com/webosose/libpbnjson/llms.txt This section demonstrates how to incrementally parse JSON from a stream of input chunks using `jdomparser_new`, `jdomparser_feed`, and `jdomparser_get_result`. This is useful when the complete JSON value is needed but the input arrives in pieces. ```APIDOC ## DOM Stream Parsing — `jdomparser_new` / `jdomparser_feed` / `jdomparser_get_result` Incremental DOM parsing that accumulates a full `jvalue_ref` tree from a stream of input chunks. Use when the complete JSON value is needed but the input arrives in pieces. ```c #include #include #include int main(void) { jdomparser_ref parser = jdomparser_new(jschema_all()); const char *parts[] = { "{\"x\":", "42,",ಸ್ಯ"y":true}", NULL }; for (int i = 0; parts[i]; i++) { if (!jdomparser_feed(parser, parts[i], (int)strlen(parts[i]))) { fprintf(stderr, "Feed error: %s\n", jdomparser_get_error(parser)); jdomparser_release(&parser); return 1; } } if (!jdomparser_end(parser)) { fprintf(stderr, "End error: %s\n", jdomparser_get_error(parser)); jdomparser_release(&parser); return 1; } jvalue_ref result = jdomparser_get_result(parser); printf("%s\n", jvalue_stringify(result)); // Output: {"x":42,"y":true} jdomparser_release(&parser); return 0; } ``` ``` -------------------------------- ### Define Schema Directory Macro Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/test/CMakeLists.txt Defines a preprocessor macro that specifies the directory where schema files are located in the build environment. ```cmake add_definitions(-DSCHEMAS_DIR="${CMAKE_CURRENT_BINARY_DIR}/schemas/") ``` -------------------------------- ### SAX Stream Parsing with C API Source: https://context7.com/webosose/libpbnjson/llms.txt Implements event-driven, zero-allocation incremental JSON parsing using the C API. Ideal for large payloads received in chunks. Requires registering callback functions for JSON tokens. ```c #include #include #include typedef struct { int depth; } MyCtx; static bool on_object_start(JSAXContextRef ctx) { MyCtx *c = (MyCtx *)jsax_getContext(ctx); printf("%*s{\n", c->depth * 2, ""); c->depth++; return true; } static bool on_object_end(JSAXContextRef ctx) { MyCtx *c = (MyCtx *)jsax_getContext(ctx); c->depth--; printf("%*s}\n", c->depth * 2, ""); return true; } static bool on_string(JSAXContextRef ctx, const char *s, size_t len) { MyCtx *c = (MyCtx *)jsax_getContext(ctx); printf("%*sstring: %.*s\n", c->depth * 2, "", (int)len, s); return true; } int main(void) { PJSAXCallbacks cbs = {0}; cbs.m_objstart = on_object_start; cbs.m_objend = on_object_end; cbs.m_string = on_string; MyCtx ctx = { .depth = 0 }; jsaxparser_ref parser = jsaxparser_new(jschema_all(), &cbs, &ctx); // Simulate chunked input const char *chunk1 = "{\"key\":\"val"; const char *chunk2 = "ue\"}"; if (!jsaxparser_feed(parser, chunk1, (int)strlen(chunk1)) || !jsaxparser_feed(parser, chunk2, (int)strlen(chunk2)) || !jsaxparser_end(parser)) { fprintf(stderr, "Parse error: %s\n", jsaxparser_get_error(parser)); } // Output: // { // string: value // } jsaxparser_release(&parser); return 0; } ``` -------------------------------- ### Serialize DOM to JSON String Source: https://context7.com/webosose/libpbnjson/llms.txt Converts a DOM tree back to a compact or pretty-printed JSON string. The returned pointer is valid for the lifetime of the jvalue_ref. ```c #include #include int main(void) { jvalue_ref obj = jobject_create_var( jkeyval(J_CSTR_TO_JVAL("host"), jstring_create("localhost")), jkeyval(J_CSTR_TO_JVAL("port"), jnumber_create_i32(8080)), J_END_OBJ_DECL ); // Compact printf("compact: %s\n", jvalue_stringify(obj)); // Output: compact: {"host":"localhost","port":8080} // Pretty-printed with 2-space indent printf("pretty:\n%s\n", jvalue_prettify(obj, " ")); // Output: // pretty: // { // "host": "localhost", // "port": 8080 // } j_release(&obj); return 0; } ``` -------------------------------- ### Parse JSON File to DOM with C API Source: https://context7.com/webosose/libpbnjson/llms.txt Reads and parses a JSON document directly from a file path using the C API. Validates against a provided schema. Errors are reported via a jerror pointer. ```c #include #include int main(void) { jerror *err = NULL; jvalue_ref root = jdom_fcreate("/etc/config/settings.json", jschema_all(), &err); if (!jis_valid(root)) { fprintf(stderr, "Failed to load file: %s\n", jerror_message(err)); jerror_free(err); return 1; } printf("JSON: %s\n", jvalue_stringify(root)); j_release(&root); return 0; } ``` -------------------------------- ### Conditional Test Building Source: https://github.com/webosose/libpbnjson/blob/master/src/CMakeLists.txt Conditionally builds the test suite if the WEBOS_CONFIG_BUILD_TESTS variable is set to true. Otherwise, it skips tests and prints a status message. ```cmake if(WEBOS_CONFIG_BUILD_TESTS) set(WITH_QTCREATOR FALSE CACHE BOOL "Enable better Qt Creator integration") add_subdirectory(test) else() message(STATUS "Skipping all unit tests") endif() ``` -------------------------------- ### Conditional Test Subdirectory Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Conditionally adds the 'test' subdirectory and enables testing if the WEBOS_CONFIG_BUILD_TESTS option is set to true. This allows for building tests only when needed. ```cmake if(WEBOS_CONFIG_BUILD_TESTS) add_subdirectory(test) enable_testing() endif() ``` -------------------------------- ### Custom Target for JSON Schema Grammar Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Defines a custom target 'json_schema_grammar' that echoes a message indicating its creation. This target is a prerequisite for the custom command that generates the grammar C file. ```cmake add_custom_target( json_schema_grammar echo "Creating json_schema_grammar.c" ) ``` -------------------------------- ### Incremental DOM Parsing with jdomparser Source: https://context7.com/webosose/libpbnjson/llms.txt Use for parsing JSON from a stream when the complete JSON value is needed. Input is fed in chunks. ```c #include #include #include int main(void) { jdomparser_ref parser = jdomparser_new(jschema_all()); const char *parts[] = { "{\"x\":", "42,", "\"y\":true}", NULL }; for (int i = 0; parts[i]; i++) { if (!jdomparser_feed(parser, parts[i], (int)strlen(parts[i]))) { fprintf(stderr, "Feed error: %s\n", jdomparser_get_error(parser)); jdomparser_release(&parser); return 1; } } if (!jdomparser_end(parser)) { fprintf(stderr, "End error: %s\n", jdomparser_get_error(parser)); jdomparser_release(&parser); return 1; } jvalue_ref result = jdomparser_get_result(parser); printf("%s\n", jvalue_stringify(result)); // Output: {"x":42,"y":true} jdomparser_release(&parser); return 0; } ``` -------------------------------- ### GPERF Code Generation Function Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Defines a CMake function 'gperf_generate' to automate the creation of C header files from GPERF input files. It sets the generated file as a generated source and adds a custom command to run GPERF. ```cmake function(gperf_generate source target) set_source_files_properties(${target} GENERATED) add_custom_command( SOURCE ${source} TARGET ${target} COMMAND ${GPERF} -t ${CMAKE_CURRENT_SOURCE_DIR}/${source} > ${target} OUTPUTS ${target} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${source} ) endfunction() ``` -------------------------------- ### Validate JSON against Schema Source: https://context7.com/webosose/libpbnjson/llms.txt Creates a compiled schema from a JSON string and validates a DOM value against it. Handles both valid and invalid payloads, reporting errors. ```c #include #include int main(void) { const char *schema_str = "{" " \"type\": \"object\", ``` -------------------------------- ### Link Libraries for Schema Validation Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/validation/CMakeLists.txt Links the 'schema_validation' library with its private dependencies, including 'jvalue' and external libraries like GLib2, YAJL, URIPARSER, and GMP. ```cmake target_link_libraries( schema_validation LINK_PRIVATE jvalue ${GLIB2_LDFLAGS} ${YAJL_LDFLAGS} ${URIPARSER_LDFLAGS} ${GMP_LIBRARY} ) ``` -------------------------------- ### Check for GCC Atomics Source: https://github.com/webosose/libpbnjson/blob/master/src/pbnjson_c/CMakeLists.txt Verifies if the compiler supports GCC-style atomic built-ins. This is used to enable atomic operations if available. ```cmake check_cxx_source_compiles( "int main() { int f; __sync_fetch_and_add(&f, 1); __sync_fetch_and_sub(&f, 1); __sync_add_and_fetch(&f, 1); __sync_sub_and_fetch(&f, 1); __sync_bool_compare_and_swap(&f, 1, 0); return 0; }" HAVE_GCC_ATOMICS) ```