javascriptarraystuples

Handling tuples in URL query


I got myself into a big mess trying to add support for arrays in query arguments for an API.

The way I am handling this now is join array by commas

const params = new URLSearchParams()
params.append("arrParam", arr.join(","))

And on the sever I am splitting by comma. This works just of one dimension arrays.

Problem now is that I have an argument that is supposed to be a tuple, like ["abc", 0] And I should be able to pass array of tuples too, in the query. That means I need to support multidimensional arrays.

Is there an abstract way of doing this, that would work for any array/array of tuples, without adding a "special case" on both client and server?


Solution

  • Query parameters can be repeated, it's explicitly allowed. So this can be your first dimension of your array, and each value can be comma separated:

    const params = new URLSearchParams();
    params.append('a', '1,2');
    params.append('a', '3,4');
    console.log(params.toString());

    Now hopefully your server side is properly implemented to parse query parameters into a multi-dict or otherwise treat repeated parameters correctly, to allow you to unparse it easily into an array of two-tuples.

    To represent even more dimensions… rethink what you're doing. You'd probably want to POST a JSON request body then.