JSON for Modern C++  3.5.0
faq.md
1 # FAQ
2 
3 ## Parsing
4 
5 ### How can I parse from a string?
6 
7 ```cpp
8 json j = json::parse("[1,2,3,4]");
9 ```
10 
11 You 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
16 std::ifstream i("your_file.json");
17 json j = json::parse(i);
18 ```
19 
20 ## Serialization
21 
22 ### How can I serialize a JSON value
23 
24 ```cpp
25 std::cout << j << std::endl;
26 ```
27 
28 This is equivalent to
29 
30 ```cpp
31 std::string s = j.dump();
32 std::cout << s << std::endl;
33 ```
34 
35 ### How can I pretty-print a JSON value
36 
37 ```cpp
38 std::cout << std::setw(4) << j << std::endl;
39 ```
40 
41 This is equivalent to
42 
43 ```cpp
44 std::string s = j.dump(4);
45 std::cout << s << std::endl;
46 ```
47 
48 The 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
55 for (json& val : j)
56 {
57  // val is a reference for the current value
58 }
59 ```
60 
61 This 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
66 for (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 
76 You can also use an iteration wrapper and use range for:
77 
78 ```cpp
79 for (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 ```