jason icon indicating copy to clipboard operation
jason copied to clipboard

Why '/' not valid in JSON key?

Open abs opened this issue 1 year ago • 2 comments

Heya!

I'm compiling some generated code that looks sort of like this:

@derive Jason.Encoder
defstruct [
:hello,
:"hello/world"
]

It's failing because of:

image

It seems that '/' is perfectly valid in a JSON key - what's the reason for having this check here?

abs avatar Dec 02 '23 23:12 abs

Because the derived or compile-time encoded keys need to be the same across all the escape options since they won't be re-escaped during encoding. In particular for escape: :html_safe the "hello/world" key would need to be escaped as "hello\/world".

michalmuskala avatar Dec 03 '23 15:12 michalmuskala

Thanks Michał

Because the derived or compile-time encoded keys need to be the same across all the escape options since they won't be re-escaped during encoding. In particular for escape: :html_safe the "hello/world" key would need to be escaped as "hello\/world".

I have two follow-up questions:

  1. When I run this:

Jason.encode(%{"aaa/bbb" => "ccc/ddd"}, escape: :html_safe)

I get:

{:ok, "{\"aaa\\/bbb\":\"ccc\\/ddd\"}"}

Wouldn't it work the same way if "aaa/bbb" was allowed through @derive Jason.Encoder?

  1. I'm just curious whether it might make sense to make the limitation a bit more targeted - for example, as a footnote or special case to the :html_safe option - instead of forbidding all use of keys containing the / in the @derive directive?

(I'm using https://github.com/OpenAPITools/openapi-generator-cli to generate servers based on OpenAPI specifications, and if a specification happens to have a key with a slash in it, the generated Elixir code simply doesn't compile.)

abs avatar Dec 03 '23 19:12 abs