Let's look at a simple example of how to use YAJL in RPG to parse a JSON string and generate a JSON string. This example assumes you have YAJL installed and configured on your IBM i system.

Parsing JSON

Parse a JSON string and extract values from it:

**free
ctl-opt dftactgrp(*no) actgrp(*new);

// Include YAJL header
dcl-pr yajl_parse int(10);
  jsonPointer pointer;
  jsonString pointer;
end-pr;

dcl-pr yajl_getValue pointer;
  jsonPointer pointer;
  key pointer;
end-pr;

dcl-pr yajl_free pointer;
  jsonPointer pointer;
end-pr;

// JSON string to parse
dcl-s jsonString varchar(1024) inz('{"name": "John", "age": 30, "city": "New York"}');
dcl-s name varchar(50);
dcl-s age int(10);
dcl-s city varchar(50);

// Parse the JSON string
jsonPointer = yajl_parse(%addr(jsonString));

// Get values from the parsed JSON
name = %str(yajl_getValue(jsonPointer, %addr('name')));
age = yajl_getValue(jsonPointer, %addr('age'));
city = %str(yajl_getValue(jsonPointer, %addr('city')));

// Output the values
dsply 'Name: ' + name;
dsply 'Age: ' + %char(age);
dsply 'City: ' + city;

// Free the JSON pointer
yajl_free(jsonPointer);

*inlr = *on;

Generating JSON

Create a JSON string from RPG variables:

**free
ctl-opt dftactgrp(*no) actgrp(*new);

// Include YAJL header
dcl-pr yajl_gen pointer;
  jsonString pointer;
end-pr;

dcl-pr yajl_string pointer;
  jsonString pointer;
end-pr;

dcl-pr yajl_free pointer;
  jsonString pointer;
end-pr;

// Variables to include in JSON
dcl-s name varchar(50) inz('John');
dcl-s age int(10) inz(30);
dcl-s city varchar(50) inz('New York');

// Generate JSON
jsonString = yajl_gen();
yajl_string(jsonString, %addr('name'), name);
yajl_string(jsonString, %addr('age'), age);
yajl_string(jsonString, %addr('city'), city);

// Output the JSON string
dsply %str(jsonString);

// Free the JSON string
yajl_free(jsonString);

*inlr = *on;

Simple Right?

  • Make sure to include the YAJL library in your RPG program.
  • The above examples are simplified for demonstration purposes. Error handling and more complex JSON structures may require additional code.
  • The actual function names and parameters may vary based on the specific implementation of YAJL on your system, so refer to the YAJL documentation for precise details.

This should give you a good starting point for working with YAJL in RPG on IBM i!

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>