metosin / jsonista

Clojure library for fast JSON encoding and decoding.
https://cljdoc.org/d/metosin/jsonista
Eclipse Public License 2.0
417 stars 30 forks source link

Recursive encoder and decoder options #23

Closed jellelicht closed 5 years ago

jellelicht commented 5 years ago

I would like to convert my clojure keywords :like-this-one to strings "likeThisOne". This is currently doable by hooking into :encode-key-fn and :decode-key-fn. This only applies to top level keys though, and any nested keys are simply converted to strings as usual.

Example {:a-long-key { :broken-here 27} } <=> { "aLongKey": { "broken-here": 27} }

How can I do this recursively, so it also applies to nested keys?

mvarela commented 5 years ago

I am using camel-snake-kebab for handling this type of transformation, and your example seems to work as expected on 0.2.4:

(def mapper (jta/object-mapper
             {:encode-key-fn (comp csk/->camelCase name)
              :decode-key-fn  csk/->kebab-case-keyword}))
(jta/write-value-as-string {:a-long-key { :broken-here 27} } mapper)

{"aLongKey":{"brokenHere":27}}

jellelicht commented 5 years ago

It is rather in converting the other way around that I am having these problems (in the specific context of POST'ing a bit of json to my webserver).

mvarela commented 5 years ago

If you read the output of the code above, it seems to work ok:

(jta/read-value
 (jta/write-value-as-string
  {:a-long-key { :broken-here 27} } mapper)
 mapper)

{:a-long-key {:broken-here 27}}

Which version of the library are you using? Do you have some sample JSON to test?

jellelicht commented 5 years ago

sorry for the noise, it was a mistake in how I was calling jsonista. Thanks for the suggestions, everything works how I expect it to now :+1:

mvarela commented 5 years ago

Glad to hear it worked out :)