Repository navigation
Expand file tree
/
Copy pathio.cpp
More file actions
67 lines (61 loc) · 2.03 KB
/
Copy pathio.cpp
File metadata and controls
67 lines (61 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
*
* @file io.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira. All rights reserved.
* https://github.com/vixcpp/vix
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Vix.cpp
* @brief Demonstrates parsing, writing, and reloading JSON with Vix.cpp helpers.
*
* This example shows how to:
* - Parse a JSON string with `loads()`.
* - Write it safely to disk using `dump_file()` (atomic operation).
* - Reload the same file using `load_file()`.
* - Print the formatted JSON using `dumps()`.
*
* The `dump_file()` function writes to a temporary file (with `.tmp` suffix)
* before renaming it atomically to prevent corruption — making it suitable
* for configuration storage, caching, or transactional file operations.
*
* ### Example Output
* ```
* {
* "a": 1,
* "b": [
* 10,
* 20
* ]
* }
* ```
*
* @see vix::json::loads
* @see vix::json::dump_file
* @see vix::json::load_file
* @see vix::json::dumps
*/
#include <vix/json/json.hpp>
#include <iostream>
int main()
{
using namespace vix::json;
// ---------------------------------------------------------------------
// Parse a JSON string into a Json object
// ---------------------------------------------------------------------
auto j = loads(R"({"a":1,"b":[10,20]})");
// ---------------------------------------------------------------------
// Write JSON to disk safely (atomic write using .tmp)
// ---------------------------------------------------------------------
dump_file("out.json", j, 2);
// ---------------------------------------------------------------------
// Read the same file back into a new Json object
// ---------------------------------------------------------------------
auto j2 = load_file("out.json");
// ---------------------------------------------------------------------
// Pretty-print the reloaded JSON to stdout
// ---------------------------------------------------------------------
std::cout << dumps(j2, 2) << "\n";
}