libkazv
Loading...
Searching...
No Matches
json-utils.hpp
Go to the documentation of this file.
1/*
2 * This file is part of libkazv.
3 * SPDX-FileCopyrightText: 2020-2023 tusooa <tusooa@kazv.moe>
4 * SPDX-License-Identifier: AGPL-3.0-or-later
5 */
6
7#pragma once
8#include "libkazv-config.hpp"
9
10#include <optional>
11#include <functional>
12#include <nlohmann/json.hpp>
13
14namespace Kazv
15{
16 template<class Jsonish, class Key, class Func>
17 bool hasAtThat(Jsonish &&j, Key &&k, Func &&f)
18 {
19 return j.contains(k)
20 && std::invoke(std::forward<Func>(f), std::forward<Jsonish>(j)[std::forward<Key>(k)]);
21 }
22
23 // https://spec.matrix.org/v1.8/client-server-api/#conditions-1
24 // non-compound canonical JSON values: strings, integers in the range of [-(2**53)+1, (2**53)-1], booleans, and null.
26 {
27 return j.is_string()
28 || (j.is_number_integer()
29 && j.template get<long long>() <= 9007199254740991LL
30 && j.template get<long long>() >= -9007199254740991LL)
31 || j.is_boolean()
32 || j.is_null();
33 }
34
35 template<class Jsonish, class RangeT>
36 std::optional<std::decay_t<Jsonish>> getInJson(Jsonish &&j, RangeT &&path, std::size_t index = 0)
37 {
38 if (index >= path.size()) {
39 return std::optional<std::decay_t<Jsonish>>(std::forward<Jsonish>(j));
40 }
41
42 auto currentSegment = path[index];
43 if (j.is_object() && j.contains(currentSegment)) {
44 return getInJson(std::forward<Jsonish>(j)[currentSegment], std::forward<RangeT>(path), index + 1);
45 }
46
47 return std::nullopt;
48 }
49}
A RangeT is an ordered collection that can be iterated through.
Definition range-t.hpp:21
Definition location.hpp:10
std::optional< std::decay_t< Jsonish > > getInJson(Jsonish &&j, RangeT &&path, std::size_t index=0)
Definition json-utils.hpp:36
bool hasAtThat(Jsonish &&j, Key &&k, Func &&f)
Definition json-utils.hpp:17
nlohmann::json json
Definition jsonwrap.hpp:20
bool isNonCompoundCanonicalJsonValue(const nlohmann::json &j)
Definition json-utils.hpp:25