program ReadJSON;
{$mode objfpc}{$H+}
uses
Classes, SysUtils, fpjson, jsonparser;
const
cFilename = 'input.json';
var
fsJSONFile: TFileStream;
jJSONData, jJSONObjectField: TJSONData;
jJSONObject: TJSONObject;
index: Integer;
begin
WriteLN('Example of JSON reader for maurbio v0.1');
WriteLN;
if FileExists(cFilename) then
begin
fsJSONFile:= TFileStream.Create(cFilename, fmOpenRead or fmShareDenyWrite);
try
jJSONData:= GetJSON(fsJSONFile);
try
if jJSONData.JSONType = jtObject then
begin
jJSONObject:= TJSONObject(jJSONData);
// By knowing the fields in advance
WriteLN('--- When you know the fields: ---');
WriteLN('address1: ':15, jJSONObject.Strings['address1']);
WriteLN('address2: ':15, jJSONObject.Strings['address2']);
WriteLN('author: ':15, jJSONObject.Strings['author']);
WriteLN('city: ':15, jJSONObject.Strings['city']);
WriteLN('country: ':15, jJSONObject.Strings['country']);
WriteLN('dataset1: ':15, jJSONObject.Strings['dataset1']);
WriteLN('dataset2: ':15, jJSONObject.Strings['dataset2']);
WriteLN('datetime: ':15, jJSONObject.Strings['datetime']);
WriteLN('description: ':15, jJSONObject.Strings['description']);
WriteLN('elevation: ':15, jJSONObject.Strings['elevation']);
WriteLN('email: ':15, jJSONObject.Strings['email']);
WriteLN('fax: ':15, jJSONObject.Strings['fax']);
WriteLN('funding: ':15, jJSONObject.Strings['funding']);
WriteLN('institution: ':15, jJSONObject.Strings['institution']);
WriteLN('latitude: ':15, jJSONObject.Strings['latitude']);
WriteLN('locality: ':15, jJSONObject.Strings['locality']);
WriteLN('longitude: ':15, jJSONObject.Strings['longitude']);
WriteLN('method: ':15, jJSONObject.Strings['method']);
WriteLN('phone: ':15, jJSONObject.Strings['phone']);
WriteLN('province: ':15, jJSONObject.Strings['province']);
WriteLN('role: ':15, jJSONObject.Strings['role']);
WriteLN('size: ':15, jJSONObject.Strings['size']);
WriteLN('state: ':15, jJSONObject.Strings['state']);
WriteLN('title: ':15, jJSONObject.Strings['title']);
WriteLN('uf: ':15, jJSONObject.Strings['uf']);
WriteLN('website: ':15, jJSONObject.Strings['website']);
WriteLN('zip: ':15, jJSONObject.Strings['zip']);
WriteLN;
// By key/value pair
WriteLN('--- When you iterate through fields: ---');
for index:= 0 to Pred(jJSONObject.Count) do
begin
jJSONObjectField:= jJSONObject.Items[index];
WriteLN(jJSONObject.Names[index]+': ':15, jJSONObjectField.AsString);
end;
end
else
begin
WriteLN('Was expecting that the JSON contained a single JSON Object.');
end;
finally
// Do NOT forget to free this object or you'll have leaks
// Since this object contains all the above objects we used
// no need to free those, just the overall _parent_.
jJSONData.Free;
end;
finally
fsJSONFile.Free;
end;
end
else
begin
WriteLN('Cannot find file ' + cFilename);
end;
end.