# Uni-JSON Example Usage

This directory contains a complete example of how to use the uni-json library with custom C bindings.

## Files

- `simple.c` - Main example demonstrating JSON parsing
- `c_bindings.c` - C implementation of the uni-json parser bindings
- `Makefile` - Build system for the example

## Building

```bash
# Build the example
make

# Or build and run
make run

# Clean build files
make clean
```

## Usage

The example parses the JSON string:
```json
{"ACTION":"add", "SUBSYSTEM":"input"}
```

And displays the parsed key-value pairs.

## How it works

1. **C Bindings**: The `c_bindings.c` file implements the `uni_json_p_binding` interface required by the uni-json library. This includes:

   - Memory management functions (`make_object`, `free_object`, etc.)
   - String handling (`make_work_string`, `add_2_string`, `finalize_string`)
   - Array and primitive type handling
   - Error handling

2. **Data Structures**: The example defines internal structures that match what the bindings create:
   - `struct uni_json_value` - Represents any JSON value
   - `struct uni_json_object_entry` - Represents key-value pairs in objects
   - `struct uni_json_array_entry` - Represents elements in arrays

3. **Parsing Process**:
   - Call `uni_json_parse()` with the JSON data and bindings
   - The parser calls the binding functions to create the JSON structure
   - Access the parsed data through the returned structure

## Key Implementation Details

### String Handling
The uni-json library uses a two-phase string creation process:
1. `make_work_string()` - Creates a working string object
2. `add_2_string()` - Adds string data (for escaped characters)
3. `finalize_string()` - Finalizes the string with the complete data

If no escape characters are present, `make_work_string()` may not be called, and `finalize_string()` receives NULL as the working string.

### Memory Management
- All objects are allocated with `malloc()`
- The `free_object()` function recursively frees the entire JSON structure
- String data is allocated separately and freed in `free_string()`

### Error Handling
- The `on_error()` callback receives parsing errors
- Error codes are defined in `uni_json_parser.h`

## Integration with VDev

This example demonstrates the pattern used by VDev for JSON parsing in device events. The same binding approach can be used for:

- Parsing device event JSON
- Configuration file parsing
- Network protocol parsing
- Any JSON processing needs

## Extending the Example

To add support for additional JSON features:

1. Extend the data structures in both files
2. Implement the corresponding binding functions
3. Add handling in the parsing logic

For example, to add number parsing:
```c
// In the data structure
double num;

// In the binding
static void *make_number(uint8_t *data, size_t len, unsigned flags)
{
    // Convert string to number
    // Return allocated number object
}
```
