Welcome! Please see the About page for a little more info on how this works.

0 votes
in data.json by
recategorized by


I'm new to Clojure and didn't find answer so please sorry if this is not issue at all.

lets say we have data:

{:space1/value 123 :space2/value 456}

and use clojure.data.json as serialiser:

(clojure.data.json/write-str {:space1/value 123 :space2/value 456})
=> "{\"value\":123,\"value\":456}"

As you see result is not what one can expect.
Obvious solution would be to provide own key-fn and forget about it. But I spend a lot of time catching bug caused by default implementation and like to save time of other

1 Answer

+1 vote

The documentation is clear on why it happens:

:key-fn function

    Single-argument function called on map keys; return value will
    replace the property names in the output. Must return a
    string. Default calls clojure.core/name on symbols and
    keywords and clojure.core/str on everything else.

It cannot be changed post factum because it would break existing code.

So, in other words, having buggy default implementation is preferred over fixing that would possible broke something?
it's not a bug, it's a behavior.
You prefer the `(subs  (str %) 1)` keyfn by  default.
Another one, for example, me, prefer `(name %)` by defualt.

The behavior is well working and well documented. No I can't see a "bug".
About seeing a bug.
Personally I consider that producing JSON with duplicate keys is a bug. Wondering that someone can disagree with this.

Closer to my point. What is `default` implementation? I expect *correct* results from `default` implementation, not the results that match mine/ones needs or aesthetic preferences. And we have opposite here.
`{"a" "str" (symbol "a") "sym" :a "kw"}` will produce `{"a": "str", "a": "sym", "a", "kw"}` using your "correct" solution.

Duped keys is not invalid JSON. On most browser impls, "the last one" will be the "real one"

Personally, I map manually every qualified field into a unqualified, to generate JSON