Skip to content

JSONDecoder fails, same code works on x86_64 #2223

@flavio

Description

@flavio

Big disclaimer: I'm new to swift, I spent the last days playing around with it because it seems the WASM support you are working on is already pretty good. Kudos to you 👏

The problem

I'm trying to decode an instance of a custom struct starting from a JSON object. I tried to leverage the JSONDecoder class from the foundation module. It looks like the same code works on x86_64, but does not on WASM.

Any help is appreciated ❤️

How to reproduce the issue

I created an empty folder, inside of that I wrote this simple main.swift file:

import Foundation

struct Message: Decodable {
    enum CodingKeys: String, CodingKey {
        case author
        case body
    }

    let author: String
    let body: String
}

let json = Data("""
{
    "author": "flavio",
    "body": "hello world"
}
""".utf8)

do {
    let msg: Message = try JSONDecoder().decode(Message.self, from: json)
    print("automatic decoding worked fine")
    print(msg)
} catch {
    print("automatic decoding DID NOT work as expected")
    print(error)

    let obj = try? JSONSerialization.jsonObject(with: json, options: [])

    if let dictionary = obj as? [String: Any] {
      for key in ["author", "body"] {
        let value = dictionary[key] as! String
        print("\(key)-> \(value)\n")
      }
    }
}

I compiled the code on my Linux system using the latest version of the ghcr.io/swiftwasm/swift container.

I produced a x86_64 binary via swiftc main.swift, this produces a main binary.
I produced a WASM binary via swiftc -target wasm32-unknown-wasi main.swift -o main.wasm, this produces a main.wasm binary.

The regular x86_64 binary can be run without any issue:

$ ./main 
automatic decoding worked fine
Message(author: "flavio", body: "hello world")

The WASM file instead fails:

$ wasmtime run main.wasm
valueNotFound(json.Message, Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value.", underlyingError: nil))
author-> flavio

body-> hello world

As you can see the WASM binary cannot use the JSONDecode class, but it can use JSONSerialization just fine.

Environment details

Swift compiler

SwiftWasm Swift version 5.3 (swiftlang-5.3.0)
Target: x86_64-unknown-linux-gnu

Coming from the container ghcr.io/swiftwasm/swift@sha256:763cb6e1a18ce18ebc71634186c4d18d718a594bab149077478695ab9b2e0fd4

WASM runtime

I'm using wasmtime version 0.21.0

Host

My host is openSUSE Tumbleweed, running on a x86_64 machine.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions