javascriptjsonjson-api

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.


Solution

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