Skip to content

Fetch: Support object literal serialization (as JSON) #213

Open
@friday

Description

@friday

Since #128 was fixed, the built-in object serialization was removed in favor of either diy-serialization or hooks.

I'm proposing to reintroduce object serialization, but as JSON, not query strings, because of the many issues and implementation details to settle with query strings.

Problems with query strings

  • Converting nested data to to query strings is somewhat complex, likely adding at least ~20-30 lines of code.
  • Some form of recursion is needed to optimally "walk" over the object. Tail call optimisation is currently only implemented in Chrome (I think?) so this could cause stack overflows on huge nested objects.
  • The only supported data type is string, so it's not possible on the receiving end to distinguish between "true" vs true or 5 vs "5" or ["a"] vs {0:'a'}.
  • It's not a standardized format. From the jQuery docs: "Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead."
  • Because it's not a universally agreed-upon spec, many serializers have optional arguments for small details such as how to encode arrays, or encoding spaces as + or %20. Besides making the serializer more complex and harder to both maintain and use, this also means fetch would have to support these arguments as well, or only support the defaults. I think this partly defeats the purpose of supporting object serialization in fetch.

JSON (application/json) doesn't have these problems

  • No custom method needed. JSON.stringify() is supported since IE8.
  • No stack overflow risk
  • No ambiguity or string coercion.
  • No difference between server implementations or extra arguments needed.
  • Very few implementation details to settle, making it very easy to implement.

On the negative side, it could be confusing if strings are treated as query strings (current behavior) but object literals are serialized as application/json (this proposal). Depending on your server environment it could also take some extra effort to support.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions