square brackets in query parameter keys

Viewed 3290

I need to GET data from an API that uses square brackets as part of the parameter name. I didn't write the API, so don't shoot the messenger!

Edit: I should have noted, this code will run on node (server-side), not in the browser.

I'm using Axios in Javascript, and this is my axios call:

axios.get(url, {params: {queryParams}})
    .then(res => {
        brands = res.data;
        console.log(res.data);
    })
    .catch(error => {
        console.log( '\n\n\n\n')
        console.log(error);
    });

The params are as follows. For brevity, I'm showing the three different formats I've tried (direct character, escaped and ASCII encoded), but in each attempt, I've passed the three parameters with the same format.

Set the query parameters
let queryParams = {
    "tables": table,
    "manifest": manifest,
    "where[0][0]": field,
    "where%5B0%5D%5B1%5D": "%3D",
    "where\\[0\\]\\[2\\]": searchValue,
    "ordery_by": "id%2C%20ASC",
    "limit": "100",
    "app": "json",
    'client_key': authkey
}

In all cases, axios seems to transform the parameters into a javascript web token.

If, on the other hand, I concatenate the parameters to the URL as a string, the request works, and I get the data I expected.

let fullPath = url.concat(
    "?tables=", table,
    "&manifest=", manifest,
    "&where%5B0%5D%5B0%5D=", field,
    "&where%5B0%5D%5B1%5D=", "%3D",
    "&where%5B0%5D%5B2%5D=", searchValue,
    "&ordery_by=", "id%2C%20ASC",
    "&limit=", "100",
    "&app=", "json",
    "&client_key=", authkey
)

While I have a workaround solution (as shown above), is there a way doing this with a proper parameters object?

1 Answers

If you are doing this in browser you could use the URLSearchParams() to iterate a human readable object and have it create the query string.

There is also a similar module available for Node

axios supports passing a URLSearchParams object as params argument also

let queryParams = {
    "tables": 1,
    "manifest": 2,
    "where[0][0]": 3,
    "where[0][1]": "=",
    "where[0][2]": 4,
    "ordery_by": "id,ASC",
    "limit": "100",
    "app": "json",
    'client_key': 'abc'
}

const sParams = new URLSearchParams(Object.entries(queryParams));

console.log('query string')
console.log(sParams.toString())
console.log('sParam entries')
console.log(JSON.stringify([...sParams]))
.as-console-wrapper {   max-height: 100%!important;top:0;}

Going a step further you can construct the full url with URL constructor

const url = new URL('https://myApi.com')
url.search = new URLSearchParams(Object.entries(queryParams));

console.log(url.href)
Related