jsonpath.pp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. program jsonpath;
  2. {$mode objfpc}{$h+}
  3. uses sysutils, classes,iostream,fpjson, jsonparser;
  4. Procedure Usage(Msg : String);
  5. begin
  6. Writeln('Usage : jsonpath <path> [<file>]');
  7. Writeln('Reads JSON from <file> or standard input if the <file> argument is not present');
  8. Writeln('calculates <path> and prints path to stdout');
  9. Writeln('if <path> does not exist in the JSON, null is printed');
  10. Halt(Ord(Msg<>''));
  11. end;
  12. Var
  13. S : TStream;
  14. M : TMemoryStream;
  15. D,P : TJSONData;
  16. begin
  17. if (ParamCount<1) then
  18. Usage('Need path expression');
  19. if (ParamStr(1)='-h') or (ParamStr(1)='--help') then
  20. usage('');
  21. if (ParamCount>1) then
  22. S:=TFileStream.Create(ParamStr(2),fmOpenRead or fmShareDenyNone)
  23. else
  24. S:=TIOStream.Create(iosInput);
  25. D:=Nil;
  26. M:=Nil;
  27. P:=Nil;
  28. try
  29. M:=TMemoryStream.Create;
  30. M.CopyFrom(S,0);
  31. M.Position:=0;
  32. D:=GetJSON(M);
  33. if D<>Nil then
  34. P:=D.FindPath(ParamStr(1));
  35. if Not Assigned(P) then
  36. Writeln('null')
  37. else
  38. if P.JSONType in [jtArray,jtObject] then
  39. Writeln(P.AsJSON)
  40. else
  41. Writeln(P.AsString);
  42. Finally
  43. M.Free;
  44. S.Free;
  45. D.Free;
  46. end;
  47. end.