0

I am using Knack to solve a business process issue, however to ensure it's success I need to run a daily script to sync the data between Knack and our HR system.

Knack uses a REST API and I want to apply a filter to the GET call so that I don't have to populate a local table in order to compare the data.

Knack requires a JSON array like the example below to be encoded in the URL in order to filter the results returned. The example shows how to do this in Javascript but I cannot work out how to do this in Powershell would anyone be able to assist?

 // Request route
var api_url = 'https://api.knack.com/v1/objects/object_1/records';

// Prepare filters
var filters = {
  'match': 'or',
  'rules': [
             {
               'field':'field_1',
               'operator':'is',
               'value':'Dodgit'
             },
             {
               'field':'field_1',
               'operator':'is blank'
             }
           ]
};

// Add filters to route
api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));

1 Answer 1

2

You can do the following:

$api_url = 'https://api.knack.com/v1/objects/object_1/records'
$filters = @'
{
  'match': 'or',
  'rules': [
             {
               'field':'field_1',
               'operator':'is',
               'value':'Dodgit'
             },
             {
               'field':'field_1',
               'operator':'is blank'
             }
           ]
}
'@
$CompressedFilters = $filters | ConvertFrom-Json | ConvertTo-Json -Depth 10 -Compress
$encodedUri = "{0}?filters={1}" -f $api_url,[System.Web.HttpUtility]::UrlEncode($CompressedFilters)

Explanation:

$filters is defined as a here-string. $filters is piped into ConvertFrom-Json and then to ConvertTo-Json in order to compress the JSON data easily. However, that does swap single quotes for double quotes.

UrlEncode() from the System.Web.HttpUtility .NET class encodes special characters in URLs.

-f is the string format operator. This helps to build your URI string. The final URI is stored in $encodedUri.

NOTE: The [System.Web.HttpUtility]::UrlEncode encodes special characters with lowercase hex characters. If your system requires uppercase hex characters, then use [System.Net.WebUtility]::UrlEncode instead.

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

1 Comment

Thank you so much this is perfect for what I needed! Worked straight away!

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.