Skip to content

decode.field traverses prototype chain on JS target #918

@jtdowney

Description

@jtdowney

On the JavaScript target, decode.field (and probably decode.at and decode.subfield) succeed for keys inherited from Object.prototype (like toString and constructor). The Erlang target reports these as missing. The same Gleam source compiled for the two targets, therefore, produces different decoder results on the same input.

import gleam/dynamic/decode
import gleam/io
import gleam/json
import gleam/string

pub fn main() {
  let decoder = {
    use name <- decode.field("toString", decode.dynamic)
    decode.success(string.inspect(name))
  }

  let value = json.parse("{}", decoder)
  io.println(string.inspect(value))
  // JS: Ok("//fn() { ... }")
  // Erlang: Error(UnableToDecode([DecodeError("Field", "Nothing", ["toString"])]))
}

Using Object.hasOwn instead of the in keyword should prevent this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions