or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-manipulation.mddatetime-functions.mdexpressions.mdindex.mdnumeric-functions.mdstring-functions.mdutility-functions.md
tile.json

utility-functions.mddocs/

0

# Utility Functions

1

2

Encoding functions, type checking, and utility operations for JSONata expressions.

3

4

## Capabilities

5

6

### Encoding and Decoding Functions

7

8

#### Base64 Functions

9

10

Encode and decode strings using Base64 encoding.

11

12

```javascript { .api }

13

/**

14

* Encode string to Base64

15

* @param str - String to encode

16

* @returns Base64 encoded string

17

*/

18

function $base64encode(str);

19

20

/**

21

* Decode Base64 string

22

* @param str - Base64 encoded string to decode

23

* @returns Decoded string

24

*/

25

function $base64decode(str);

26

```

27

28

**Usage Examples:**

29

30

```javascript

31

// Basic encoding/decoding

32

const encoded = await jsonata('$base64encode("Hello World")').evaluate({}); // "SGVsbG8gV29ybGQ="

33

const decoded = await jsonata('$base64decode("SGVsbG8gV29ybGQ=")').evaluate({}); // "Hello World"

34

35

// Process user data

36

const user = {

37

username: "john.doe",

38

password: "secret123"

39

};

40

const encoded_pass = await jsonata('{"username": username, "password": $base64encode(password)}').evaluate(user);

41

42

// Encode/decode arrays of strings

43

const data = { messages: ["Hello", "World", "JSONata"] };

44

const encoded_msgs = await jsonata('messages.$base64encode($)').evaluate(data);

45

const decoded_msgs = await jsonata('encoded_msgs.$base64decode($)').evaluate({ encoded_msgs });

46

```

47

48

#### URL Encoding Functions

49

50

Encode and decode URLs and URL components.

51

52

```javascript { .api }

53

/**

54

* Encode string for use in URL component

55

* @param str - String to encode

56

* @returns URL component encoded string

57

*/

58

function $encodeUrlComponent(str);

59

60

/**

61

* Encode complete URL

62

* @param str - URL string to encode

63

* @returns URL encoded string

64

*/

65

function $encodeUrl(str);

66

67

/**

68

* Decode URL component

69

* @param str - URL component encoded string to decode

70

* @returns Decoded string

71

*/

72

function $decodeUrlComponent(str);

73

74

/**

75

* Decode complete URL

76

* @param str - URL encoded string to decode

77

* @returns Decoded URL string

78

*/

79

function $decodeUrl(str);

80

```

81

82

**Usage Examples:**

83

84

```javascript

85

// URL component encoding for query parameters

86

const query = await jsonata('$encodeUrlComponent("hello world & more")').evaluate({}); // "hello%20world%20%26%20more"

87

const decoded = await jsonata('$decodeUrlComponent("hello%20world%20%26%20more")').evaluate({}); // "hello world & more"

88

89

// Build query string

90

const params = {

91

search: "john doe",

92

category: "users & admins",

93

limit: "50"

94

};

95

const queryString = await jsonata('$keys($).($encodeUrlComponent($) & "=" & $encodeUrlComponent($lookup($$, $))).join("&")').evaluate(params);

96

// "search=john%20doe&category=users%20%26%20admins&limit=50"

97

98

// Process form data

99

const form = {

100

fields: [

101

{ name: "full name", value: "John Doe Jr." },

102

{ name: "email", value: "john@example.com" },

103

{ name: "comment", value: "Hello & welcome!" }

104

]

105

};

106

const encoded_form = await jsonata('fields.{"name": $encodeUrlComponent(name), "value": $encodeUrlComponent(value)}').evaluate(form);

107

```

108

109

### Type Checking and Conversion

110

111

#### Type Function

112

113

Returns the type of a value as a string.

114

115

```javascript { .api }

116

/**

117

* Get type of value

118

* @param value - Value to check type of

119

* @returns String representing the type

120

*/

121

function $type(value);

122

```

123

124

**Usage Examples:**

125

126

```javascript

127

// Check types of various values

128

const types = await jsonata(`{

129

"number": $type(42),

130

"string": $type("hello"),

131

"boolean": $type(true),

132

"array": $type([1,2,3]),

133

"object": $type({"key": "value"}),

134

"null": $type(null)

135

}`).evaluate({});

136

// { number: "number", string: "string", boolean: "boolean", array: "array", object: "object", null: "null" }

137

138

// Filter by type

139

const mixed = {

140

values: [1, "hello", true, [1,2], {"a": 1}, null, 3.14]

141

};

142

const numbers = await jsonata('values[$type($) = "number"]').evaluate(mixed); // [1, 3.14]

143

const strings = await jsonata('values[$type($) = "string"]').evaluate(mixed); // ["hello"]

144

145

// Type-safe operations

146

const data = { input: "123" };

147

const processed = await jsonata(`

148

$type(input) = "string" ? $number(input) : input

149

`).evaluate(data); // 123

150

```

151

152

#### Boolean Conversion

153

154

Converts a value to boolean according to JSONata truthiness rules.

155

156

```javascript { .api }

157

/**

158

* Convert value to boolean

159

* @param arg - Value to convert

160

* @returns Boolean representation of the value

161

*/

162

function $boolean(arg);

163

```

164

165

**Usage Examples:**

166

167

```javascript

168

// Convert various values to boolean

169

const booleans = await jsonata(`{

170

"number": $boolean(42), // true

171

"zero": $boolean(0), // false

172

"string": $boolean("hello"), // true

173

"empty": $boolean(""), // false

174

"array": $boolean([1,2,3]), // true

175

"emptyArray": $boolean([]), // false

176

"object": $boolean({}), // false

177

"null": $boolean(null), // false

178

"undefined": $boolean(undefined) // false

179

}`).evaluate({});

180

181

// Conditional logic

182

const user = { name: "", email: "john@example.com" };

183

const hasName = await jsonata('$boolean(name)').evaluate(user); // false

184

const hasEmail = await jsonata('$boolean(email)').evaluate(user); // true

185

186

// Filter truthy values

187

const data = { values: [0, 1, "", "hello", [], [1], {}, {"a": 1}, null, false, true] };

188

const truthy = await jsonata('values[$boolean($)]').evaluate(data); // [1, "hello", [1], true]

189

```

190

191

#### Not Function

192

193

Returns the logical NOT of a value.

194

195

```javascript { .api }

196

/**

197

* Logical NOT operation

198

* @param arg - Value to negate

199

* @returns Boolean negation of the value

200

*/

201

function $not(arg);

202

```

203

204

**Usage Examples:**

205

206

```javascript

207

// Basic NOT operations

208

const results = await jsonata(`{

209

"true": $not(true), // false

210

"false": $not(false), // true

211

"truthy": $not("hello"), // false

212

"falsy": $not(""), // true

213

"number": $not(42), // false

214

"zero": $not(0) // true

215

}`).evaluate({});

216

217

// Conditional logic

218

const user = { active: false, banned: true };

219

const canLogin = await jsonata('active and $not(banned)').evaluate(user); // false

220

221

// Filter using NOT

222

const items = {

223

products: [

224

{ name: "Laptop", available: true },

225

{ name: "Mouse", available: false },

226

{ name: "Keyboard", available: true }

227

]

228

};

229

const unavailable = await jsonata('products[$not(available)]').evaluate(items);

230

// [{ name: "Mouse", available: false }]

231

```

232

233

### Existence and Error Handling

234

235

#### Exists Function

236

237

Tests if a value exists (is not null or undefined).

238

239

```javascript { .api }

240

/**

241

* Test if value exists (not null/undefined)

242

* @param arg - Value to test

243

* @returns Boolean indicating if value exists

244

*/

245

function $exists(arg);

246

```

247

248

**Usage Examples:**

249

250

```javascript

251

// Test existence of values

252

const data = {

253

name: "John",

254

age: null,

255

email: undefined,

256

active: false

257

};

258

259

const exists = await jsonata(`{

260

"name": $exists(name), // true

261

"age": $exists(age), // false

262

"email": $exists(email), // false

263

"active": $exists(active), // true

264

"missing": $exists(missing) // false

265

}`).evaluate(data);

266

267

// Filter existing values

268

const users = {

269

users: [

270

{ name: "Alice", email: "alice@example.com" },

271

{ name: "Bob", email: null },

272

{ name: "Charlie" }

273

]

274

};

275

const withEmail = await jsonata('users[$exists(email)]').evaluate(users);

276

// [{ name: "Alice", email: "alice@example.com" }]

277

278

// Conditional processing

279

const profile = { name: "John", bio: "Developer" };

280

const display = await jsonata(`{

281

"name": name,

282

"bio": $exists(bio) ? bio : "No bio available"

283

}`).evaluate(profile);

284

```

285

286

#### Error Function

287

288

Throws an error with an optional message.

289

290

```javascript { .api }

291

/**

292

* Throw error with optional message

293

* @param message - Optional error message

294

* @throws Error with specified message

295

*/

296

function $error(message);

297

```

298

299

**Usage Examples:**

300

301

```javascript

302

// Throw error with message

303

try {

304

await jsonata('$error("Something went wrong")').evaluate({});

305

} catch (error) {

306

console.log(error.message); // "Something went wrong"

307

}

308

309

// Conditional error throwing

310

const user = { age: -5 };

311

try {

312

const result = await jsonata('age < 0 ? $error("Age cannot be negative") : age').evaluate(user);

313

} catch (error) {

314

console.log(error.message); // "Age cannot be negative"

315

}

316

317

// Validation with errors

318

const data = { email: "invalid-email" };

319

const validation = jsonata(`

320

$contains(email, "@") ? email : $error("Invalid email format")

321

`);

322

```

323

324

#### Assert Function

325

326

Asserts that a condition is true, throwing an error if false.

327

328

```javascript { .api }

329

/**

330

* Assert condition is true

331

* @param condition - Condition to test

332

* @param message - Optional error message if assertion fails

333

* @throws Error if condition is false

334

*/

335

function $assert(condition, message);

336

```

337

338

**Usage Examples:**

339

340

```javascript

341

// Basic assertions

342

const user = { name: "John", age: 30 };

343

344

// This passes

345

await jsonata('$assert($exists(name), "Name is required")').evaluate(user);

346

347

// This would throw

348

try {

349

await jsonata('$assert(age > 50, "User must be over 50")').evaluate(user);

350

} catch (error) {

351

console.log(error.message); // "User must be over 50"

352

}

353

354

// Multiple assertions

355

const data = {

356

users: [

357

{ id: 1, name: "Alice" },

358

{ id: 2, name: "Bob" }

359

]

360

};

361

362

const validation = jsonata(`

363

$assert($count(users) > 0, "Users array cannot be empty");

364

$assert($all(users, function($u) { $exists($u.id) and $exists($u.name) }), "All users must have id and name");

365

users

366

`);

367

368

// Use in data processing pipeline

369

const processUser = jsonata(`

370

$assert($exists(email), "Email is required");

371

$assert($contains(email, "@"), "Email must contain @");

372

$assert($length(name) > 0, "Name cannot be empty");

373

{

374

"id": $uuid(),

375

"name": name,

376

"email": $lowercase(email)

377

}

378

`);

379

```

380

381

## Advanced Utility Patterns

382

383

### Validation Patterns

384

385

```javascript

386

// Email validation

387

const validateEmail = jsonata(`

388

$assert($exists(email), "Email is required");

389

$assert($type(email) = "string", "Email must be a string");

390

$assert($contains(email, "@") and $contains(email, "."), "Invalid email format");

391

email

392

`);

393

394

// Number range validation

395

const validateAge = jsonata(`

396

$assert($exists(age), "Age is required");

397

$assert($type(age) = "number", "Age must be a number");

398

$assert(age >= 0 and age <= 150, "Age must be between 0 and 150");

399

age

400

`);

401

402

// Array validation

403

const validateArray = jsonata(`

404

$assert($type(data) = "array", "Data must be an array");

405

$assert($count(data) > 0, "Array cannot be empty");

406

$assert($all(data, function($item) { $type($item) = "number" }), "All items must be numbers");

407

data

408

`);

409

```

410

411

### Type-Safe Operations

412

413

```javascript

414

// Safe string operations

415

const safeStringOp = jsonata(`

416

$type(input) = "string" ? $uppercase(input) : $string(input)

417

`);

418

419

// Safe numeric operations

420

const safeNumericOp = jsonata(`

421

$type(input) = "number" ? input * 2 : $number(input) * 2

422

`);

423

424

// Safe array operations

425

const safeArrayOp = jsonata(`

426

$type(input) = "array" ? $count(input) : $count([input])

427

`);

428

```

429

430

### Debugging Utilities

431

432

```javascript

433

// Debug information

434

const debugInfo = jsonata(`{

435

"type": $type($),

436

"exists": $exists($),

437

"boolean": $boolean($),

438

"string": $string($),

439

"length": $type($) = "array" or $type($) = "string" ? $length($) : null

440

}`);

441

442

// Conditional debugging

443

const conditionalDebug = jsonata(`

444

debug = true ?

445

$merge([

446

$,

447

{"_debug": {"type": $type($), "processed_at": $now()}}

448

]) :

449

$

450

`);

451

```