Is there a way to not escape slashes when parsing JSON?
Steven Schveighoffer
schveiguy at gmail.com
Mon Feb 21 04:02:23 UTC 2022
On Monday, 21 February 2022 at 03:42:55 UTC, bachmeier wrote:
> I tried this
>
> ```d
> import std.json, std.stdio;
>
> void main() {
> writeln(parseJSON(`{"a": "path/file"}`,
> JSONOptions.doNotEscapeSlashes));
> }
> ```
>
> but the output is
>
> ```
> {"a":"path\/file"}
> ```
>
> Is there a way to avoid the escaping of the forward slash? Is
> there some reason I should want to escape the forward slash?
The options are applied on parsing or output but do not stay with
the item! So just because you parsed without allowing escapes on
slashes doesn't mean the output will use that option.
2 ways I found:
```d
// 1. allocate a string to display
writeln(parseJson(...).toString(JSONOptions.doNotEscapeSlashes));
// 2. wrap so you can hook the output range version of toString
struct NoEscapeJson
{
JSONValue json;
void toString(Out)(Out outputrange) const
{
json.toString(outputrange,
JSONOptions.doNotEscapeSlashes);
}
}
writeln(NoEscapeJson(parseJson(...)));
```
-Steve
More information about the Digitalmars-d-learn
mailing list