michalmuskala / jason

A blazing fast JSON parser and generator in pure Elixir.
Other
1.61k stars 169 forks source link

Why '/' not valid in JSON key? #179

Open abs opened 10 months ago

abs commented 10 months ago

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?

michalmuskala commented 10 months ago

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".

abs commented 10 months ago

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.)