0

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.

3
  • The result probably should not be in JSON format since that would produce a single string. I think what you want is an array or an object. JSON doesn't refer to either of those. Commented Feb 14, 2024 at 15:47
  • I just want something I can easily extract the values from - you’re right, and I did mean an object, not JSON Commented Feb 14, 2024 at 15:50
  • If you use the standard query string middleware in Express, you should be able to access them like req.get['industries.id']. Commented Feb 14, 2024 at 15:54

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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
    }
        

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.