aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/json/easy_parse/json_easy_parser.cpp
blob: 0d4e1c52ffee56faad7d21f86eb8dd4c37ab0389 (plain) (blame)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#include "json_easy_parser.h"
#include <library/cpp/json/json_reader.h>
#include <util/string/cast.h> 
#include <util/string/split.h>
#include <util/string/strip.h>

namespace NJson {
    static TString MAP_IDENTIFIER = "{}";
    static TString ARRAY_IDENTIFIER = "[]";
    static TString ANY_IDENTIFIER = "*";

    static void ParsePath(TString path, TVector<TPathElem>* res) {
        TVector<const char*> parts;
        Split(path.begin(), '/', &parts);
        for (size_t n = 0; n < parts.size(); ++n) {
            TString part = Strip(parts[n]); 
            if (!part.empty()) {
                if (part[0] != '[') {
                    res->push_back(TPathElem(NImpl::MAP));
                    res->push_back(TPathElem(part));
                } else {
                    int arrayCounter;
                    try {
                        arrayCounter = FromString<int>(part.substr(1, part.length() - 2));
                    } catch (yexception&) {
                        arrayCounter = -1;
                    }
                    res->push_back(TPathElem(arrayCounter));
                }
            }
        }
    }

    void TJsonParser::AddField(const TString& path, bool nonEmpty) {
        Fields.emplace_back();
        Fields.back().NonEmpty = nonEmpty;
        ParsePath(path, &Fields.back().Path);
    }

    TString TJsonParser::ConvertToTabDelimited(const TString& json) const {
        TStringInput in(json);
        TStringStream out;
        ConvertToTabDelimited(in, out);
        return out.Str();
    }

    class TRewriteJsonImpl: public NJson::TJsonCallbacks {
        const TJsonParser& Parent;
        TVector<TString> FieldValues;
        TVector<TPathElem> Stack;
        bool ShouldUpdateOnArrayChange;
        int CurrentFieldIdx;
        bool HasFormatError;

    private:
        static bool PathElementMatch(const TPathElem& templ, const TPathElem& real) {
            if (templ.Type != real.Type)
                return false;
            if (templ.Type == NImpl::ARRAY)
                return templ.ArrayCounter == -1 || templ.ArrayCounter == real.ArrayCounter;
            if (templ.Type == NImpl::MAP_KEY)
                return templ.Key == ANY_IDENTIFIER || templ.Key == real.Key;
            return true;
        }

        bool CheckFilter(const TVector<TPathElem>& path) const {
            if (Stack.size() < path.size())
                return false;
            for (size_t n = 0; n < path.size(); ++n) {
                if (!PathElementMatch(path[n], Stack[n]))
                    return false;
            }
            return true;
        }

        void UpdateRule() {
            for (size_t n = 0; n < Parent.Fields.size(); ++n) {
                if (FieldValues[n].empty() && CheckFilter(Parent.Fields[n].Path)) {
                    CurrentFieldIdx = n;
                    return;
                }
            }
            CurrentFieldIdx = -1;
        }

        void Pop() {
            Stack.pop_back();
        }

        void IncreaseArrayCounter() {
            if (!Stack.empty() && Stack.back().Type == NImpl::ARRAY) {
                ++Stack.back().ArrayCounter;
                if (ShouldUpdateOnArrayChange)
                    UpdateRule();
            }
        }

        template <class T>
        bool OnValue(const T& val) {
            IncreaseArrayCounter();
            if (CurrentFieldIdx >= 0) {
                FieldValues[CurrentFieldIdx] = ToString(val);
                UpdateRule();
            }
            return true;
        }

    public:
        TRewriteJsonImpl(const TJsonParser& parent)
            : Parent(parent)
            , FieldValues(parent.Fields.size())
            , ShouldUpdateOnArrayChange(false)
            , CurrentFieldIdx(-1)
            , HasFormatError(false)
        {
            for (size_t n = 0; n < Parent.Fields.size(); ++n) {
                if (!Parent.Fields[n].Path.empty() && Parent.Fields[n].Path.back().Type == NImpl::ARRAY)
                    ShouldUpdateOnArrayChange = true;
            }
        }

        bool OnOpenMap() override {
            IncreaseArrayCounter();
            Stack.push_back(TPathElem(NImpl::MAP));
            if (CurrentFieldIdx >= 0)
                HasFormatError = true;
            else
                UpdateRule();
            return true;
        }

        bool OnOpenArray() override {
            IncreaseArrayCounter();
            Stack.push_back(TPathElem(-1));
            if (CurrentFieldIdx >= 0)
                HasFormatError = true;
            else
                UpdateRule();
            return true;
        }

        bool OnCloseMap() override {
            while (!Stack.empty() && Stack.back().Type != NImpl::MAP)
                Pop();
            if (!Stack.empty())
                Pop();
            UpdateRule();
            return true;
        }

        bool OnCloseArray() override {
            if (!Stack.empty())
                Pop();
            UpdateRule();
            return true;
        }

        bool OnMapKey(const TStringBuf& key) override {
            if (!Stack.empty() && Stack.back().Type == NImpl::MAP_KEY) {
                Pop();
                UpdateRule();
            }
            Stack.push_back(TPathElem(TString{key}));
            if (CurrentFieldIdx >= 0)
                HasFormatError = true;
            else
                UpdateRule();
            return true;
        }

        bool OnBoolean(bool b) override {
            return OnValue(b);
        }

        bool OnInteger(long long i) override {
            return OnValue(i);
        }

        bool OnDouble(double f) override {
            return OnValue(f);
        }

        bool OnString(const TStringBuf& str) override {
            return OnValue(str);
        }

        bool IsOK() const {
            if (HasFormatError)
                return false;
            for (size_t n = 0; n < FieldValues.size(); ++n)
                if (Parent.Fields[n].NonEmpty && FieldValues[n].empty())
                    return false;
            return true;
        }

        void WriteTo(IOutputStream& out) const {
            for (size_t n = 0; n < FieldValues.size(); ++n)
                out << "\t" << FieldValues[n];
        }

        void WriteTo(TVector<TString>* res) const {
            *res = FieldValues;
        }
    };

    void TJsonParser::ConvertToTabDelimited(IInputStream& in, IOutputStream& out) const {
        TRewriteJsonImpl impl(*this);
        ReadJson(&in, &impl);
        if (impl.IsOK()) {
            out << Prefix;
            impl.WriteTo(out);
            out.Flush();
        }
    }

    bool TJsonParser::Parse(const TString& json, TVector<TString>* res) const {
        TRewriteJsonImpl impl(*this);
        TStringInput in(json);
        ReadJson(&in, &impl);
        if (impl.IsOK()) {
            impl.WriteTo(res);
            return true;
        } else
            return false;
    }

    //struct TTestMe {
    //    TTestMe() {
    //        TJsonParser worker;
    //        worker.AddField("/x/y/z", true);
    //        TString ret1 = worker.ConvertToTabDelimited("{ \"x\" : { \"y\" : { \"w\" : 1, \"z\" : 2 } } }");
    //        TString ret2 = worker.ConvertToTabDelimited(" [1, 2, 3, 4, 5] ");
    //    }
    //} testMe;

}