jsonlddocumentprocessor.cpp 1.62 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
   SPDX-FileCopyrightText: 2017-2021 Volker Krause <vkrause@kde.org>

   SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "jsonlddocumentprocessor.h"

#include <KItinerary/ExtractorResult>

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

using namespace KItinerary;

static bool contentStartsWith(const QByteArray &data, char s)
{
19
    for (unsigned char c : data) {
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
        if (std::isspace(c)) {
            continue;
        }
        return c == s;
    }
    return false;
}

bool JsonLdDocumentProcessor::canHandleData(const QByteArray &encodedData, QStringView fileName) const
{
    return contentStartsWith(encodedData, '[')
        || contentStartsWith(encodedData, '{')
        || fileName.endsWith(QLatin1String(".json"), Qt::CaseInsensitive)
        || fileName.endsWith(QLatin1String(".jsonld"), Qt::CaseInsensitive);
}

ExtractorDocumentNode JsonLdDocumentProcessor::createNodeFromData(const QByteArray &encodedData) const
{
    QJsonParseError error;
    const auto doc = QJsonDocument::fromJson(encodedData, &error);
    if (error.error != QJsonParseError::NoError) {
        return {};
    }

    QJsonArray data;
    if (doc.isObject()) {
        data.push_back(doc.object());
    } else if (doc.isArray()) {
        data = doc.array();
    } else {
        return {};
    }

    ExtractorDocumentNode node;
    node.setContent(data);
    return node;
}

void JsonLdDocumentProcessor::preExtract(ExtractorDocumentNode &node, [[maybe_unused]] const ExtractorEngine *engine) const
{
    // pass through JSON data, so the using code can apply post-processing to that
    node.addResult(node.content<QJsonArray>());
}