Search code examples
jsonrestclojuremicroservices

Clojure name binding to REST JSON data


I'm a Frontend Engineer, our team is switching many of our old services to micro services written in clojure. The main issue I'm seeing is that clojure naming conventions prefer hyphens to-separate-words in variable names. This means if you straight map variables into JSON any JS consumer would need to access this data using bracket notation e.g. response['to-separate-words']. This is obviously not ideal. I thought this would be a easy best practice to lookup but I've been looking for an hour and it seems like all the docs I read avoid this issue but using single words. Has anyone else dealt with this.


Solution

  • You might use camel-snake-kebab library which supports most of the combinations. You can plug it in into most of the JSON libraries for Clojure (cheshire, cli-json, data.json - as mentioned by Elogent) as they usually have an option to provide a function for handling property name mangling.

    For example with cheshire:

    Generate JSON with camel case property names:

    (cheshire.core/generate-string {:my-clojure-key "abc"} 
                                   {:key-fn camel-snake-kebab.core/->camelCaseString})
    

    Result:

    {"myClojureKey":"abc"}
    

    Parse JSON to get map with kebab case keys:

    (cheshire.core/parse-string "{\"myClojureKey\":\"abc\"}" 
                                camel-snake-kebab.core/->kebab-case-keyword)
    

    Result:

    {:my-clojure-key "abc"}
    

    There is also an example for data.json in camel-snake-kebab readme.