summaryrefslogtreecommitdiff
path: root/AK/JsonPath.cpp
blob: 6a9f2dad3708b030750a1cd56a9cd055c3ef7a8a (plain)
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
/*
 * Copyright (c) 2020, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/JsonObject.h>
#include <AK/JsonPath.h>
#include <AK/JsonValue.h>

namespace AK {

JsonPathElement JsonPathElement::any_array_element { Kind::AnyIndex };
JsonPathElement JsonPathElement::any_object_element { Kind::AnyKey };

JsonValue JsonPath::resolve(JsonValue const& top_root) const
{
    auto root = top_root;
    for (auto const& element : *this) {
        switch (element.kind()) {
        case JsonPathElement::Kind::Key:
            root = JsonValue { root.as_object().get(element.key()) };
            break;
        case JsonPathElement::Kind::Index:
            root = JsonValue { root.as_array().at(element.index()) };
            break;
        default:
            VERIFY_NOT_REACHED();
        }
    }
    return root;
}

String JsonPath::to_string() const
{
    StringBuilder builder;
    builder.append("{ ."sv);
    for (auto const& el : *this) {
        builder.append("sv > "sv);
        builder.append(el.to_string());
    }
    builder.append("sv }"sv);
    return builder.to_string();
}

}