diff --git a/README.md b/README.md index 5ace317..a95f046 100644 --- a/README.md +++ b/README.md @@ -433,22 +433,17 @@ structure (and its substructures) in descending alphabetical order: ## JSON parser and emitter -Once you have an `XStructure` or `XField` data object, you can easily convert them to JSON string representation, as: +Once you have an `XStructure` data object, you can easily convert it to JSON string representation, as: ```c XStructure *s = ... // Obtain a JSON string representation of the structure 's'. char *json = xjsonToString(s); - - - XField *f = ... - // Obtain a JSON string representation of the structure 's'. - char *json2 = xjsonFieldToString(f); ``` -Or, you can do the reverse and create an `XStructure` from its JSON representation, either from a string (a -0-terminated `char` array): +The above produces a proper JSON document. Or, you can do the reverse and create an `XStructure` from its JSON +representation, either from a string (a 0-terminated `char` array): ```c int lineNumber = 0; @@ -467,17 +462,53 @@ or parse it from a file, which contains a JSON definition of the structured data } ``` -Additionally, you might just want to use JSON-style escaping for strings, and `xjsonEscape()` / `xjsonUnescape()` can -help with that too: +### Snippets +Alternatively, you can also create partial JSON snippets for individual fields, e.g.: + ```c - char *string = "\t\"This has some special characters\"\n"; + XField *f = ... + + // Obtain a JSON string snippet of the field 'f'. + char *json = xjsonFieldToString(f); +``` + +For example, for a numerical array field with 4 elements the above might generate something like: + +```json + "my-numbers": [ 1, 2, 3, 4] +``` + + +### Escaped string representations + +You might just want to use JSON-style escaping for strings, and `xjsonEscape()` / `xjsonUnescape()` can help with that +too. Suppose you have a C string that you want to escape... + +```c + // This corresponds to 2 lines e.g. in a file, like: + // + // "This has some + // special characters" + // + char *string = "\"This has some\n\t special characters\""; // Escape the special character, e.g. replace `\n` with `\` + `n` etc... char *escaped = xjsonEscape(string); - - // And reverse, from escaped form to ASCII (should be the same as the original string...) - char *string2 = xjsonUnescape(escaped); +``` + +If you now print `escaped` to a file or the standard output, it will show up there are: + +```txt + \"This has some\n\t special characters\" +``` + +And the reverse, suppose you read back the above line from an input, containing the escaped form, and want to +reconstruct from it the original C string with the special characters in it: + +```c + // And reverse, from escaped form to ASCII (e.g. `\` + `n` --> `\n`) + char *string = xjsonUnescape(escaped); ```