Ric
Ric

Reputation: 3468

Parse parameters/values from JSON API query with JavaScript

How do I parse a JSON API style query in JavaScript? An example query would be:

/search?filter[industries.id]=1&filter[locations.id]=3&filter[item_type][0]=temporary

I want to extract the filter fields and value (and ideally other JSON API parameters). I don’t mind too much what format the result is in, whether it’s an oject or array etc. I need to be able to check if a filter exists and get it’s value.

This is client side, not on the server.

Happy to use a library is there is one, but can’t find one.

Upvotes: 0

Views: 161

Answers (2)

James
James

Reputation: 22246

You can use the browser's URLSearchParams interface to do most of the work. Here's one way that includes splitting the key (like, "filter[industries.id]") into two separate properties.

let someURL = "/search?filter[industries.id]=1&filter[locations.id]=3&filter[item_type][0]=temporary";

let searchParamString = someURL.split("?")[1]; // keep everything after the ?

let usp = new URLSearchParams(searchParamString);
let result = [];
for (let [key, value] of usp.entries()) {
  let [type, field, ...rest] = key.split("[");
  field = "[" + field;
  if (rest.length) field += "[" + rest.join("[");
  result.push({type, field, value});
}

console.log(result);

Upvotes: 2

Oleg Imanilov
Oleg Imanilov

Reputation: 2751

The easiest and obvious way to handle such requests would be to convert it into JSON like this:

{
 "industries.id": 1, 
 "locations.id": 3, 
 "item_type": ["temporary"]
}

Here is an example of code to do it


    const params = new URLSearchParams("filter[industries.id]=1&filter[locations.id]=3&filter[item_type][0]=temporary");


    const result = {};

    for (const [key, value] of params) {
        // Remove 'filter[' prefix and ']' suffix, then split by '][' for nested properties
        const path = key.replace(/^filter\[|\]$/g, '').split('][');
        // ...
        // Handle value here. Parse numbers, strings, arrays etc
        // ...
        result[path[0]] = parsedValue
    }
        

Upvotes: 0

Related Questions