# JSONEncoder bug when dictionary key is enum?

**URL:** <https://forums.swift.org/t/jsonencoder-bug-when-dictionary-key-is-enum/40418>\
**Category:** Using Swift\
**Tags:** jsonencoder\
**Created:** [September 19, 2020, 12:04am UTC](https://forums.swift.org/t/jsonencoder-bug-when-dictionary-key-is-enum/40418 "2020-09-19T00:04:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ponyboy47](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ponyboy47/32/2605_2.png) [@Ponyboy47](https://forums.swift.org/u/Ponyboy47)\
**Post date:** [September 19, 2020, 12:04am UTC](https://forums.swift.org/t/jsonencoder-bug-when-dictionary-key-is-enum/40418/1 "2020-09-19T00:04:33Z")

</div>

```swift
import Foundation
enum Foo: String, Encodable { 
    case asc
    case desc
}
let foobar: [Foo: String] = [.desc: "testing"]
let encoder = JSONEncoder()
let data = try encoder.encode(foobar)
print(String(data: data, encoding: .utf8)!)

// Prints: ["desc","testing"]

```

This is a simplified example that demonstrates an issue I have been encountering in a project I'm working on. When the key of a dictionary is an enum, the JSONEncoder encodes it as an array and not as a dictionary.

I am able to reproduce this on both swift 5.3 and 5.2.4

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [September 19, 2020, 12:07am UTC](https://forums.swift.org/t/jsonencoder-bug-when-dictionary-key-is-enum/40418/2 "2020-09-19T00:07:42Z")

</div>

You may want to check out this thread:

> [@Encoding/Decoding a Swift Dictionary to/from JSON](https://forums.swift.org/t/encoding-decoding-a-swift-dictionary-to-from-json/39989/3):
>
> Specifically, it treats Int and String as CodingKeys with the equivalent intValue/stringValue which allows it to encode as an actual dictionary as opposed to the more general types. From the last time @Lantua and I discussed this (sweat_smile), see the links below for some more background on this: If you need to specifically maintain a dictionary format here, your best bet is to encode and decode as [Int: String] but perform the conversion to Int32 afterwards.

---

<div class="post-metadata">

**Author:** ![Ponyboy47](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ponyboy47/32/2605_2.png) [@Ponyboy47](https://forums.swift.org/u/Ponyboy47)\
**Post date:** [September 19, 2020, 12:14am UTC](https://forums.swift.org/t/jsonencoder-bug-when-dictionary-key-is-enum/40418/3 "2020-09-19T00:14:23Z")

</div>

Thanks @Lantua! Good to know why it's happening although it is a frustrating limitation. Since the enum has a string rawValue I can just transform the keys to strings prior to encoding.
