Skip to content

Commit

Permalink
More json examples
Browse files Browse the repository at this point in the history
PUBLISHED_FROM=873ab3e2b5e1fcc2869cbf2577e43795677d4065
  • Loading branch information
cpq authored and cesantabot committed Dec 14, 2017
1 parent 91a2556 commit d7ade80
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,13 @@ int json_scanf_array_elem(const char *s, int len,
struct json_token *token);
```


## `json_printf()`

A helper function to scan an array item with given path and index.
Fills `token` with the matched JSON token.
Returns 0 if no array element found, otherwise non-0.

The Frozen printing API is pluggable. Out of the box, Frozen provides a way
## `json_printf()`

Frozen printing API is pluggable. Out of the box, Frozen provides a way
to print to a string buffer or to an opened file stream. It is easy to
to tell Frozen to print to another destination, for example, to a socket, etc.
Frozen does this by defining an "output context" descriptor which has
Expand Down Expand Up @@ -380,6 +379,36 @@ void *json_next_elem(const char *s, int len, void *handle, const char *path,
```

# Examples

## Print JSON configuration to a file

```c
json_fprintf("settings.json", "{ a: %d, b: %Q }", 123, "string_value");
json_prettify_file("settings.json"); // Optional
```
## Read JSON configuration from a file
```c
struct my_config { int a; char *b; } c = { .a = 0, .b = NULL };
char *content = json_fread("settings.json");
json_scanf(content, strlen(content), "{a: %d, b: %Q}", &c.a, &c.b);
```

## Modify configuration setting in a JSON file

```c
const char *settings_file_name = "settings.json", *tmp_file_name = "tmp.json";
char *content = json_fread(settings_file_name);
FILE *fp = fopen(tmp_file_name, "w");
struct json_out out = JSON_OUT_FILE(fp);
json_setf(content, strlen(content), &out, ".b", "%Q", "new_string_value");
fclose(fp);
json_prettify_file(tmp_file_name); // Optional
rename(tmp_file_name, settings_file_name);
```
# Contributions
To submit contributions, sign
Expand Down

0 comments on commit d7ade80

Please sign in to comment.