C++ Logo

std-discussion

Advanced search

Re: std::format and json objects

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 18 Apr 2023 11:23:54 -0400
On Tue, Apr 18, 2023 at 8:58 AM Federico Kircheis via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> On Tue, Apr 18, 2023 at 08:32:32AM -0400, Jason McKesson via Std-Discussion wrote:
> >On Tue, Apr 18, 2023 at 7: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?
> >
> >No tool is going to be perfect for every application, and for basic
> >tools like `format`, you have to pick *something* for your delimiter.
> >
> >Find/replace is not `format`'s job. That's the job of a regex tool.
>
> I suppose my choice of words was not ideal.
> I did not want to say I want to replace ____ with a given value, ____ is
> in this example the placeholder for the value one is going to format.
>
> I could obviously not use {} for describing the issue, maybe it would
> have been better if I've used the std::printf syntax: %s and %d

I'm confused. You say that you don't want to "replace ____ with a
given value", but you then claim that "____" is "the placeholder for
the value one is going to format".

That's what "replace" means. You're telling `format` to search through
the string for its formatting tags, and you want it to take any
instance of that formatting tag and turn it into a value from one of
its parameters. That's... replacing.

`std::format` and `std::printf` are both specialized versions of
generic string find/replace operations. The principle specialization
is that the text to be replaced is determined by the system, not by an
arbitrary input to the system. That is, `format/printf` determines
what strings it searches for.

Your needs simply do not match the powers of the specialized tool.
Therefore, a more generalized tool is appropriate. Making `format`
take different formatting tags adds complexity to a system that is
otherwise quite functional for its intended purpose.

Received on 2023-04-18 15:24:06