I'd be surprised if you could. jq
decodes its input, does its operations and encodes the resulting object as json. Upon encoding and outputting, it outputs those strings encoded in JSON and the information that there were \
s in front of /
s has long been lost. Same would happen if those /
s where initially written \u002f
. You'll find that jq
also reformats 1.0
as 1
, 1e2
as 100
, INF
as 1.7976931348623157e+308
, etc for the same reason.
However, JSON is a relatively easy file format to process reliably by hand using for instance perl regexps.
To add back the \
s before each /
in all strings except those that are object keys, you could do:
jq... |
perl -0777 -pe '
s{"(?:\\.|.)*?"(\s*:)?}{
$1 ? $& : $& =~ s{/}{\\/}gr
}ge'
Which should work correctly even if you have strings embedding "
s and \
s (like {"key": "//\"//\\"}
).
As an alternative to jq
, you could use the JSON::PP perl
module which can be told to escape slashes (though would be in all strings though):
$ json_pp -json_opt escape_slash < your-file
{"proto:\/\/some\/path":"\/\/some\/path"}
If you're already familiar with perl
, the learning curve would be less steep than having to learn the jq
syntax.
In any case while the JSON format allows /
s to be escaped as \/
(or \u002f
like for any character) those don't need to. From what I read online, that's allowed so one can embed a JSON string containing </
in an HTML <script>
tag by writing it "<\/whatever"
. That's why some JSON encoders encode those \/
as /
as that makes it more portable. But if that JSON is not meant to be embedded as is in HTML, it probably doesn't matter. And if it were, you'd likely want to have that encoding everywhere including in object keys.
a\\/b
(encoded) asa\/b
(decoded) and be able to use it correctly? If not, then there is no point in talking about JSON or usingjq
and instead treat the document as text and useawk
to do whatever you need to do since the thing that is reading the document clearly isn't a JSON parser. The thing with the stringa\/b
is that to a JSON application, that backslash does not exist. – Kusalananda Feb 26 '23 at 21:16/
s in strings except those used as object keys. – Stéphane Chazelas Feb 26 '23 at 21:27jq
to sort the keys with--sort-keys
since the tool that generated these files produced a non-deterministic order which messed up mygit
diffs. – YourMJK Feb 26 '23 at 21:47\/
instead of/
in your data in the first place?/
is not a special character in regex. One possible reason would be for exemple if you use that to create awk code, and use :/pattern/
, and dont want any '/' inside pattern to be interpreted as the end of the/.../
? But you could replace it with$0 ~ "pattern"
(or$0 ~ pattern_in_variable
) ? – Olivier Dulac Feb 27 '23 at 08:15