Zen C++ Libraries
Zero-dependency re-usable components for C++
Loading...
Searching...
No Matches
json.hpp
1#ifndef ZEN_JSON_HPP
2#define ZEN_JSON_HPP
3
4#include <memory>
5#include <istream>
6#include <ostream>
7
8#include "zen/config.hpp"
9#include "zen/transformer.hpp"
10#include "zen/value.hpp"
11#include "zen/either.hpp"
12
13ZEN_NAMESPACE_START
14
15enum class json_token_type {
16 end_of_file,
17 integer,
18 fractional,
19 array_start,
20 array_end,
21 object_start,
22 object_end,
23 comma,
24 colon,
25 kw_false,
26 kw_true,
27 kw_null,
28 identifier,
29};
30
31enum class json_parse_error {
32 unrecognised_escape_sequence,
33 unexpected_character,
34};
35
36using json_parse_result = either<json_parse_error, value>;
37
38json_parse_result parse_json(std::istream& in);
39json_parse_result parse_json(const std::string& in);
40
42 std::string indentation = "";
43};
44
45std::unique_ptr<transformer> make_json_decoder(
46 std::istream& input,
47 json_encode_opts opts = {}
48);
49
51
52};
53
54std::unique_ptr<transformer> make_json_encoder(
55 std::ostream& output,
56 json_decode_opts opts = {}
57);
58
59template<typename InputT, typename T>
60void decode_json(InputT input, T& value) {
61 auto decoder = make_json_decoder(input);
62 decode(decoder, value);
63}
64
65template<typename OutputT, typename T>
66void encode_json(OutputT output, T& value) {
67 auto encoder = make_json_encoder(output);
68 decode(encoder, value);
69}
70
71template<typename OutputT, typename T>
72void encode_json_pretty(OutputT output, T& value) {
73 json_encode_opts opts = {
74 .indentation = " ",
75 };
76 auto encoder = make_json_encoder(output, opts);
77 decode(encoder, value);
78}
79
80ZEN_NAMESPACE_END
81
82#endif // of #ifndef ZEN_JSON_HPP
A type for computations that may fail.
Definition either.hpp:124
Definition value.hpp:34
Encapsulation for computations that may fail.
Definition json.hpp:50
Definition json.hpp:41