• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# FAQ
2
3## Parsing
4
5### How can I parse from a string?
6
7```cpp
8json j = json::parse("[1,2,3,4]");
9```
10
11You can pass string literals (as above), `std::string`, `const char*` or byte containers such as `std::vector<uint8_t>`.
12
13### How can I parse from a file?
14
15```cpp
16std::ifstream i("your_file.json");
17json j = json::parse(i);
18```
19
20## Serialization
21
22### How can I serialize a JSON value
23
24```cpp
25std::cout << j << std::endl;
26```
27
28This is equivalent to
29
30```cpp
31std::string s = j.dump();
32std::cout << s << std::endl;
33```
34
35### How can I pretty-print a JSON value
36
37```cpp
38std::cout << std::setw(4) << j << std::endl;
39```
40
41This is equivalent to
42
43```cpp
44std::string s = j.dump(4);
45std::cout << s << std::endl;
46```
47
48The number `4` denotes the number of spaces used for indentation.
49
50## Iterating
51
52### How can I iterate over a JSON value?
53
54```cpp
55for (json& val : j)
56{
57    // val is a reference for the current value
58}
59```
60
61This works with any JSON value, also primitive values like numbers.
62
63### How can I access the keys when iterating over a JSON object?
64
65```cpp
66for (auto it = j.begin(); it != j.end(); ++it)
67{
68    // the value
69    json &val = it.value();
70
71    // the key (for objects)
72    const std::string &key = it.key();
73}
74```
75
76You can also use an iteration wrapper and use range for:
77
78```cpp
79for (auto it : json::iteration_wrapper(j))
80{
81    // the value
82    json &val = it.value();
83
84    // the key (for objects)
85    const std::string &key = it.key();
86}
87```
88