0
votes

I'm hoping for a bit of a "simpletons" demo\explanation for using Lazarus\Freepascal JSON parsing. I've asked a question here but all the replies are "read this" and none of them are really helping me get a grasp because the examples are bit too in-depth and I'm seeking a very simple example to help me understand how it works.

In brief, my program reads an untyped binary file in chunks of 4096 bytes. The raw data then gets converted to ASCII and stored in a string. It then goes through the variable looking for certain patterns, which, it turned out, are JSON data structures. I've currently coded the parsing the hard way using Pos and ExtractANSIString etc. But I'vesince learnt that there are JSON libraries for Lazarus & FPC, namely fcl-json, fpjson, jsonparser, jsonscanner etc.

https://bitbucket.org/reiniero/fpctwit/src http://fossies.org/unix/misc/fpcbuild-2.6.0.tar.gz:a/fpcbuild-2.6.0/fpcsrc/packages/fcl-json/src/ http://svn.freepascal.org/cgi-bin/viewvc.cgi/trunk/packages/fcl-json/examples/

However, I still can't quite work out HOW I read my string variable and parse it for JSON data and then access those JSON structures.

Can anyone give me a very simple example, to help getting me going?

My code so far (without JSON) is something like this:

try
  SourceFile.Position := 0;
  while TotalBytesRead < SourceFile.Size do
    begin 
      BytesRead := SourceFile.Read(Buffer,sizeof(Buffer));
      inc(TotalBytesRead, BytesRead);      
      StringContent := StripNonAsciiExceptCRLF(Buffer);    // A custom function to strip out binary garbage leaving just ASCII readable text     
      if Pos('MySearchValue', StringContent) > 0 then
          begin          
            // Do the parsing. This is where I need to do the JSON stuff

...

1

1 Answers

1
votes

See parsedemo.pp, specially parsestring. Just modify the doparse routine to extract whatever information you need from the j:TJSonData object.

The simpledemo.pp demonstrates how to disect a jsondata object.

Then read the src/README.txt file. It seems to hint on a bunch of properties of a jsonobject that allow to get fields by name. This only works for structures json objects like array and object.

I do agree that a demo for that would be a good thing. If you make it, please submit it to mantis.

Disclaimer: I have nothing to do with the json package, I got the above from a quick glance at the (admittedly 2.7.1) source.