utils: add json_utils

Add parseJson function to simplify json parsing:
* automatically log parsing failure
* allows single-line json parsing
* take a string_view instead of begin/end pointers
* optimize building the CharReader by reusing the CharReaderBuilder

Change-Id: I332a88fc476ee84ba400a96bc1b41515cca43c32
This commit is contained in:
Adrien Béraud
2025-02-05 15:54:50 -05:00
parent 62ab5d057a
commit f8d2ae8405
2 changed files with 51 additions and 0 deletions

40
src/json_utils.h Normal file
View File

@ -0,0 +1,40 @@
/*
* Copyright (C) 2004-2024 Savoir-faire Linux Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string_view>
#include <json/json.h>
#include <logger.h>
namespace jami {
extern const Json::CharReaderBuilder rbuilder;
inline bool parseJson(std::string_view jsonStr, Json::Value& json) {
std::string err;
auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
if (!reader->parse(jsonStr.data(),
jsonStr.data() + jsonStr.size(),
&json,
&err)) {
JAMI_WARNING("Can't parse JSON: {}\n{}", err, jsonStr);
return false;
}
return true;
}
}

View File

@ -39,8 +39,19 @@
#include <ciso646> // fix windows compiler bug
#include "json_utils.h"
namespace jami {
Json::CharReaderBuilder getJsonReaderBuilder()
{
Json::CharReaderBuilder builder;
builder["collectComments"] = false;
return builder;
}
const Json::CharReaderBuilder rbuilder = getJsonReaderBuilder();
std::string_view
userAgent()
{