C++ Logo

std-discussion

Advanced search

Re: std::format and json objects

From: Barry Revzin <barry.revzin_at_[hidden]>
Date: Tue, 18 Apr 2023 11:04:47 -0500
On Tue, Apr 18, 2023 at 6:53 AM Federico Kircheis via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> Hello, I have a question regarding std::format.
>
> The API works generally very well, but it is problematic to escape every
> { and }, especially when there are a lot of those, like in json objects.
>
> Suppose I have for example the literal
>
> R"json({
> "data": {
> "data 1": [
> {"id":1,"name":"foo"},
> {"id":2,"name":"bar"}
> ],
> "data 2": {"id":2,"name":"____"}
> },
> "otherstuff": {
> "void": [[1,42],[-1,____]]
> }
> })json"
>
> And I would like to use std::format for replacing ____ with some values.
>
> As far as I know, it is not possible to instruct std::format to use
> another pair of delimiters for a single call.
>
> Falling back to std::printf or std::cout does not seem to be the right
> solution, and escaping every { and } has drawbacks too.
>
> Was this issue ever discussed or acknowledged?
> Are there some obvious workarounds I'm missing?
>
> Best
>
> Federico
>

It is not feasible to have the placeholders in format configurable -
user-defined formatters look for } too.

I think the obvious workaround is to simply use a JSON library. Barring
that, you can always take your string literal that uses __ as a
placeholder, and then do three replaces() on { -> {{, } -> }}, and __ ->
{}.

Barry

Received on 2023-04-18 16:05:00