Is there a way to not escape slashes when parsing JSON?

bachmeier no at spam.net
Mon Feb 21 17:32:23 UTC 2022


On Monday, 21 February 2022 at 04:02:23 UTC, Steven Schveighoffer 
wrote:
> 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

I've had a chance to look into this. The documentation for 
`parseJSON` says:

```
JSONOptions options 	enable decoding string representations of 
NaN/Inf as float values
```

which looks to me as if there's no way to apply 
`doNotEscapeSlashes` while parsing. Your approach works if the 
goal is to print out the JSON as it was passed in. I don't see 
any way to work with the parsed JSON data. If I want to later 
work with element "a" and do something with "path/file", the 
value will always be "path\/file". AFAICT, I'd have to manually 
unescape every element.


More information about the Digitalmars-d-learn mailing list