babashka / json

JSON abstraction library
MIT License
30 stars 2 forks source link

`:key-fn` for encoding keys with `babashka.json/write-str` #10

Open rads opened 1 week ago

rads commented 1 week ago

Would it make sense to add :key-fn for babashka.json/write-str for encoding keys since this is already supported for decoding keys with read-str?

rads commented 1 week ago

Right now I'm using babashka.json with an HTTP API that uses snake_case.

This works:

(json/read-str s {:key-fn inflections/hyphenate})

But not this:

(json/write-str x {:key-fn inflections/underscore})
borkdude commented 1 week ago

I guess so, if the underlying libraries support it too?

rads commented 1 week ago

I can check if any of the libraries don't support this and get back to you.

rads commented 1 week ago

@borkdude: I wrote a test to show how this is done for each lib (see README to run it yourself):

https://github.com/rads/json-key-fns/blob/main/src/rads/json_key_fns.clj

The only one that doesn't support it easily is charred. Overriding the behavior requires a custom :obj-fn and the default-obj-fn is private so I had to copy-paste the implementation and modify it slightly. There are a handful of options to move forward here:

  1. Do nothing and close this issue
  2. Use the custom obj-fn with the copy-pasted code
  3. Throw an exception when using :key-fn with json/write-str when using charred
  4. Coerce the keys in babashka.json before calling charred.api/write-json-str
  5. Talk to @cnuernber to see if there is a simpler way or a possible improvement we can make to charred to make this easier

If we want to move forward with this, I can follow up with PRs and reach out to @cnuernber if needed. If it's not worth the effort, I'll go ahead and close this issue.

rads commented 1 week ago

Added another option to the list above to throw an exception if using :key-fn with charred.

rads commented 1 week ago

And one more option for coercing the keys before calling charred. 😄

borkdude commented 1 week ago

Talking to the charred author seems like a reasonable next step?

On Sat, Nov 9, 2024 at 12:02 AM Radford Smith @.***> wrote:

And one more option for coercing the keys before calling charred. 😄

— Reply to this email directly, view it on GitHub https://github.com/babashka/json/issues/10#issuecomment-2465877351, or unsubscribe https://github.com/notifications/unsubscribe-auth/AACFSBUVBOV4FLM2VP45NQTZ7U7HPAVCNFSM6AAAAABROLOI6OVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDINRVHA3TOMZVGE . You are receiving this because you were mentioned.Message ID: @.***>

-- https://www.michielborkent.nl https://www.eetvoorjeleven.nu

rads commented 1 week ago

Sounds good, I'll get back to you when I have some more info.