This problem is caused by the fact that many people use languages where a variable doesn't need to be known at compile-time. For example, PHP, JavaScript or Python are interpreted languages... they can read the JSON and build variables with the names in the JSON on-the-fly. RPG, however, is a compiled language so it needs to know the variable names at compile-time.
You may be thinking that this would somehow make working with a JavaScript/PHP/Python (etc) program to be easier than RPG. But it's not, really, when you get into the actual coding. For example, after the JSON is parsed, what are you going to do with the data? If it is JavaScript, you'd probably do something like this:
Code: Select all
if (typeof myvar.NCapi != "undefined") {
//handle NCampi
else if (typeof myvar.CAMPO0 != "undefined") {
// handle CAMPO0
}
... etc ...
So even though you don't need to hard-code the list of field names in a data structure definition, you'll still need to hard code them in the logic of the program. UNLESS they are using the key names as variable values rather than field names -- but this isn't the typical structure for that sort of thing, so I'm not thinking that's what's happening in this case.
Assuming you're willing to hard-code the list of field names, you can do so by creating an array of data strucrures where all of the fields are optional fields.
Code: Select all
**free
dcl-ds *N psds;
num_arr Int(20) Pos(372);
end-ds;
dcl-s json varchar(500);
dcl-s i int(10);
dcl-ds el qualified;
num_NCampi int(10);
NCampi char(1);
num_CAMPO0 int(10);
CAMPO0 varchar(30);
num_TIPOCAMPO0 int(10);
TIPOCAMPO0 char(1);
num_CODICE_ARTICOLO int(10);
CODICE_ARTICOLO varchar(20);
end-ds;
dcl-ds myArr likeds(el) dim(100);
json =
'[{+
"NCampi": "1"+
},+
{+
"CAMPO0": "CODICE_ARTICOLO"+
},+
{+
"TIPOCAMPO0": "1"+
},+
{+
"CODICE_ARTICOLO": "001012001"+
}]';
DATA-INTO myarr %data(json: 'case=convert countprefix=num_')
%parser('YAJLINTO');
for-each el in %subarr(myArr:1:num_arr);
if el.num_NCampi = 1;
// handle NCampi
elseif el.num_CAMPO0 = 1;
// handle NCampi
endif;
endfor;
*inlr = *on;
So you see that's not very different from what you'd have to do in another language like JavaScript. On the other hand, if the keys are really variable values rather than field names (i.e. associative arrays), your best bet would be to use the YAJL subprocedures/routines...