Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSONEncoder encodes Dictionary key as JSON value #59629

Open
20unkown13 opened this issue Jun 22, 2022 · 0 comments
Open

JSONEncoder encodes Dictionary key as JSON value #59629

20unkown13 opened this issue Jun 22, 2022 · 0 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.

Comments

@20unkown13
Copy link

Describe the bug
JSONEncoder encodes Dictionary key as JSON value if Dictionary key is Double, works as intended with String or Int

To Reproduce
Compile this code:

    //Dictionary Key is Type String
    var Key_String : [String:Dictionary<String, Int>] = ["1":["longitude":43,"latitude":53]]
    do {
        let encodedDictionary = try JSONEncoder().encode(Key_String)
        let jsonString = String(data: encodedDictionary, encoding: .utf8)!
        print("Key_String",jsonString) //{"1":{"longitude":43,"latitude":53}}
    } catch {
        print("Error: ", error)
    }
    
    //Dictionary Key is Type Double
    let Key_Double : [Double:Dictionary<String, Int>] = [1.0:["longitude":43,"latitude":53]]
    
    do {
        let encodedDictionary = try JSONEncoder().encode(Key_Double)
        let jsonString = String(data: encodedDictionary, encoding: .utf8)!
        print("Key_Double",jsonString) //[1,{"longitude":43,"latitude":53}]
    } catch {
        print("Error: ", error)
    }
    
    //Dictionary Key is Type Int
    let Key_Int : [Int:Dictionary<String, Int>] = [1:["longitude":43,"latitude":53]]

    do {
        let encodedDictionary = try JSONEncoder().encode(Key_Int)
        let jsonString = String(data: encodedDictionary, encoding: .utf8)!
        print("Key_Int   ",jsonString) //{"1":{"longitude":43,"latitude":53}}
    } catch {
        print("Error: ", error)
    }

Expected behavior
JSONEncoder should encode Dictionary Key as Key

Screenshots
image

Environment (please complete the following information):

  • OS: macOS 12.0.1
  • Xcode Version/Tag/Branch: Version 13.4.1 (13F100)
@20unkown13 20unkown13 added the bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. label Jun 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior.
Projects
None yet
Development

No branches or pull requests

1 participant