program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.Json,
System.SysUtils;
function IsEven(
const Value: Integer ): Boolean;
begin
Result := Value
mod 2 = 0;
end;
function ParseSingleExpression( AJsonArray: TJsonArray ):
string;
var
lInner : TJsonArray;
lFieldName:
string;
lOperator :
string;
lValue :
string;
begin
if AJsonArray.Count <> 1
then
raise EArgumentException.Create( '
single item in array expected' );
if not( AJsonArray.Items[ 0 ]
is TJsonArray )
then
raise EArgumentException.Create( '
array expected' );
lInner := AJsonArray.Items[ 0 ]
as TJsonArray;
if lInner.Count <> 3
then
raise EArgumentException.Create( '
three items expected' );
if not( lInner.Items[ 0 ]
is TJSONString )
then
raise EArgumentException.Create( '
string expected' );
lFieldName := lInner.Items[ 0 ].Value;
if not( lInner.Items[ 1 ]
is TJSONString )
then
raise EArgumentException.Create( '
string expected' );
lOperator := lInner.Items[ 1 ].Value;
if lInner.Items[ 2 ]
is TJSONString
then
lValue := QuotedStr( lInner.Items[ 2 ].Value )
else
lValue := lInner.Items[ 2 ].Value;
Result :=
string.Format( '
(%s %s %s)', [ lFieldName, lOperator, lValue ] );
end;
function ParseJsonExpression( AJsonArray: TJsonArray ):
string;
overload
var
I: Integer;
begin
if IsEven( AJsonArray.Count )
then
raise EArgumentException.Create( '
odd items in array expected' );
if AJsonArray.Count = 1
then
Result := ParseSingleExpression( AJsonArray )
else
begin
Result := '
( ';
for I := 0
to AJsonArray.Count - 1
do
begin
if I
mod 2 = 0
then
if AJsonArray.Items[ I ]
is TJsonArray
then
Result := Result + ParseJsonExpression( AJsonArray.Items[ I ]
as TJsonArray )
else
raise EArgumentException.Create( '
Array expected' )
else
Result := Result + '
' + AJsonArray.Items[ I ].Value + '
';
end;
Result := Result + '
)';
end;
end;
function ParseJsonExpression( AJsonStr:
string ):
string;
overload;
var
lValue: TJSONValue;
begin
lValue := TJSONObject.ParseJSONValue( AJsonStr );
try
if lValue
is TJsonArray
then
Result := ParseJsonExpression( lValue
as TJsonArray )
else
raise EArgumentException.Create( '
Fehlermeldung' );
finally
lValue.Free;
end;
end;
const
Data1 = '
[["Bezeichnung","=","Angussstutzen-Rev/B-PPTV30"]]';
Data2 = '
[[["Bezeichnung","=","Angussstutzen-Rev/B-PPTV30"]],"and",[["charge","=","11"]]]';
Data3 = '
[[["Bezeichnung","=","Angussstutzen-Rev/B-PPTV30"]],"and",[["charge","=","11"]],"and",[[["Bezeichnung","=","Angussstutzen-Rev/B-PPTV30"]],"and",[["charge","=","11"]]]]';
procedure Main;
begin
WriteLn( Data1 );
WriteLn( ParseJsonExpression( Data1 ) );
WriteLn;
WriteLn( Data2 );
WriteLn( ParseJsonExpression( Data2 ) );
WriteLn;
WriteLn( Data3 );
WriteLn( ParseJsonExpression( Data3 ) );
end;
begin
try
Main( );
except
on E:
Exception do
WriteLn( E.ClassName, '
: ', E.
Message );
end;
ReadLn;
end.