Recent

Author Topic: json goes RichMemo  (Read 2057 times)

Nicole

  • Hero Member
  • *****
  • Posts: 1303
json goes RichMemo
« on: July 03, 2025, 04:28:01 pm »
Repeatadly I use json-strings in my code.
It is hard to read.
Parsing to a string, - is even harder. I failed so many times and lost information and read error-messages...

Is there a tool, which extracts json nicely to a string to use it e.g. in Listboxes or RichMemos?
what I dream of:

- shall find out by itself which information is available
- shall be robust and quiet if the information is damaged (I cannot click away dozens of error messages)

Here comes an example of what I would like to parse to a RichMemo (one of a great amount of formats)

Code: Diff  [Select][+][-]
  1. {
  2.   "status" : "ok",
  3.   "totalResults" : 3279,
  4.   "articles" : [
  5.     {
  6.       "source" : {
  7.         "id" : "cbs-news",
  8.         "name" : "CBS News"
  9.       },
  10.       "author" : "Kerry  Breen",
  11.       "title" : "Bryan Kohberger expected to plead guilty in murders of Idaho students",
  12.       "description" : "Bryan Kohberger is expected to plead guilty in the 2022 slayings of four University of Idaho students in a deal that will spare him from the death penalty.",
  13.       "url" : "https://www.cbsnews.com/news/bryan-kohberger-university-of-idaho-student-murders-plea-hearing/",
  14.       "urlToImage" : "https://assets3.cbsnewsstatic.com/hub/i/r/2025/03/07/2f72c02f-2278-4f5f-b0a3-c9a5807156cb/thumbnail/1200x630/41dc633d26b13e8bdd42172f001325dc/kohberger.jpg",
  15.       "publishedAt" : "2025-07-02T13:02:44Z",
  16.       "content" : "Bryan Kohberger, the former criminal justice doctoral student charged in the murders of four University of Idaho students in 2022, is expected to officially plead guilty Wednesday in a deal with pros… [+4378 chars]"
  17.     },
  18.     {
  19.       "source" : {
  20.         "id" : "the-times-of-india",
  21.         "name" : "The Times of India"
  22.       },
  23.       "author" : "Global Desk",
  24.       "title" : "Elon Musk loses $12,000,000,000 in one day amid Trump feud and Tesla crash — here’s what caused second-biggest wealth wipeout in human history",
  25.       "description" : "Elon Musk just lost a jaw-dropping $12,000,000,000 in one day, and the world is watching. The loss came after a heated Trump feud and a dramatic Tesla stock crash, shaking investor confidence. As Trump threatened to pull EV tax credits and SpaceX contracts, M…",
  26.       "url" : "https://economictimes.indiatimes.com/news/international/us/elon-musk-loses-12000000000-in-one-day-amid-trump-feud-and-tesla-crash-heres-what-caused-second-biggest-wealth-wipeout-in-human-history/articleshow/122206909.cms",
  27.       "urlToImage" : "https://img.etimg.com/thumb/msid-122207336,width-1200,height-630,imgsize-118178,overlay-economictimes/articleshow.jpg",
  28.       "publishedAt" : "2025-07-02T12:52:51Z",
  29.       "content" : "Elon Musk suffers $12 billion loss in just one day amid Trump feud, Tesla stock plunge: On July 12, 2025, the worlds richest man, Elon Musk, lost a staggering $12 billion in a single day. The massive… [+6188 chars]"
  30.     },
  31.     {
  32.       "source" : {
  33.         "id" : null,
  34.         "name" : "Idnes.cz"
  35.       },
  36.       "author" : "iDNES.cz

and 1000 lines more

CM630

  • Hero Member
  • *****
  • Posts: 1616
  • Не съм сигурен, че те разбирам.
    • http://sourceforge.net/u/cm630/profile/
Re: json goes RichMemo
« Reply #1 on: July 03, 2025, 04:30:20 pm »
Before you go further in that direction - TRichMemo seems abandoned.
Лазар 4,4 32 bit (sometimes 64 bit); FPC3,2,2

rvk

  • Hero Member
  • *****
  • Posts: 6944
Re: json goes RichMemo
« Reply #2 on: July 03, 2025, 04:42:20 pm »
Before you go further in that direction - TRichMemo seems abandoned.
Or it's already perfected  :D

That set aside... This question seems more to be about a function to do prettyprint on json.
Otherwise @Nicole, what is your desired output??

paweld

  • Hero Member
  • *****
  • Posts: 1568
Re: json goes RichMemo
« Reply #3 on: July 03, 2025, 05:07:08 pm »
@Nicole: Try json viewer, eg. https://github.com/gcarreno/laz-JSON-Viewer
Best regards / Pozdrawiam
paweld

Nicole

  • Hero Member
  • *****
  • Posts: 1303
Re: json goes RichMemo
« Reply #4 on: July 03, 2025, 05:32:35 pm »
What my output would be the best for me? This hard to say.

e.g. in the case of the above news function I dream of keying in "Tesla" and see in return:

12. 11. 2024 Tesla car burnt in New York (click here for more)
 1.   3.  2025 new factory built in France (Reuters, click here to see full article)
 3.   7.  2025 Musk produces a Trump Killer Car (White House, click here for a dic pic of Trump)

and so on.
The best thing ever would be, if there would be news filters in languages I do not speak. But this is fantasy.

I am not sure, if there shall be a clickable link or not. This may cause more troubles than it solves. Better it is NOT clickable.

If RichMemo is abandoned: what do you suggest?
Once I tried this htmlView and - returned to the snapshot without it.
I never said, that CEF would be a sauries because we must not say this here. So let me put it like this: too large for me, I tried it. TMemo is even less flexible. TListView is hard to fill. TListbox makes it hard to work with the complete text.

Thank you for the link with the Laz-Json Viewer. How can I use it? Is it a component or a tool?
(at the moment I work on a Win 7 VM)

Thaddy

  • Hero Member
  • *****
  • Posts: 18729
  • To Europe: simply sell USA bonds: dollar collapses
Re: json goes RichMemo
« Reply #5 on: July 03, 2025, 05:46:10 pm »
If RichMemo is abandoned: what do you suggest?
It is not abandoned. It just does not need updates....
People like to look at the last release date and that is a wrong way of judging software quality so:
Ignore that answer, it does not expose any real knowledge.
After all, have a look at the fpc 3.2.2 release date... Nuff said.

RvK wrote about the same btw.

The full sourcecode is available, so when something needs fixing it will be fixed.
There are no open issues regarding TRichmemo that I am aware of....
« Last Edit: July 03, 2025, 06:59:03 pm by Thaddy »
If Europe sells their USA bonds the USD will collapse. Europe can affort that given average state debts. The USA can't affort that. Just an advice...

paweld

  • Hero Member
  • *****
  • Posts: 1568
Re: json goes RichMemo
« Reply #6 on: July 03, 2025, 06:56:26 pm »
Thank you for the link with the Laz-Json Viewer. How can I use it? Is it a component or a tool?
(at the moment I work on a Win 7 VM)
This is tool.
1. download source from: https://github.com/gcarreno/laz-JSON-Viewer/archive/refs/heads/master.zip
2. Unzip
3. Open in Lazarus ( src / lazJSONViewer.lpi )
4. Build

It doesn't matter if your OS is Windows or Linux
Best regards / Pozdrawiam
paweld

rvk

  • Hero Member
  • *****
  • Posts: 6944
Re: json goes RichMemo
« Reply #7 on: July 03, 2025, 07:10:25 pm »
What my output would be the best for me? This hard to say.

e.g. in the case of the above news function I dream of keying in "Tesla" and see in return:

12. 11. 2024 Tesla car burnt in New York (click here for more)
 1.   3.  2025 new factory built in France (Reuters, click here to see full article)
 3.   7.  2025 Musk produces a Trump Killer Car (White House, click here for a dic pic of Trump)

and so on.
The best thing ever would be, if there would be news filters in languages I do not speak. But this is fantasy.
That looks like you want to take something like from https://newsapi.org/ and create your own cliënt (like groundnews) to search for news  :D

There is no ready made component for you to use. You will have to create the retrieval, parsing, searching and displaying of the result yourself. I don't think the component you use to view this is very important. You can start by just using trichmemo and putting the result in there. You can also convert your results to html and use one of the htmlviewers. The most important part is creating a standalone component which retrieves and filters to your desired result. Keep the visual and functional parts separated.

So first create a TMyNews component which retrieves the data and where you can set a filter after which it spits out your results. Then you can take that result and display it like you want (converting it for RTF of HTML.

BTW. I searched for newsapi and fpc the Google AI already gave me a complete example to retrieve the newsapi.org and filter it's result to a TMemo (without me even asking for it)  ;)

creaothceann

  • Sr. Member
  • ****
  • Posts: 266
Re: json goes RichMemo
« Reply #8 on: July 03, 2025, 07:19:29 pm »
I'd first recreate the structure in code:

Code: [Select]
unit UForm_NewsArticles;


interface
uses
// ...


type
TSource = class
ID, Name : string;
end;


TArticle = class
Source                                                              : TSource;
Author, Title, Description, URL, URL_to_Image, PublishedAt, Content : string;
end;


TArticles = class
constructor Create(const SourceText : string);
destructor  Destroy;                            override;

private
var      _Articles     : array of TArticle;
var      _Status       : boolean;
function _TotalResults : integer;

public
property Status       : boolean read _Status;
property TotalResults : integer read _TotalResults;
end;


// TForm_NewsArticles definition here


implementation
uses
FpJson, JsonParser;  // https://wiki.freepascal.org/fcl-json


// ...


end.

Then write the Create constructor to call the JSON parser, while creating the structure in memory.

Then display a list of articles in a TListView (with ViewStyle = vsReport and OwnerData = True). The currently selected article can be displayed below in a TMemo or something else.
« Last Edit: July 03, 2025, 07:22:38 pm by creaothceann »

d2010

  • Sr. Member
  • ****
  • Posts: 253
Re: json goes RichMemo
« Reply #9 on: July 03, 2025, 07:47:39 pm »
Quote from: paweld link=topic=71658.msg559663#msg559663
This is tool.
1. download source from: [url
https://github.com/gcarreno/laz-JSON-Viewer/archive/refs/heads/master.zip[/url]
2. Unzip
3. Open in Lazarus ( src / lazJSONViewer.lpi )
4. Build
It doesn't matter if your OS is Windows or Linux
For one file , D:disk, in my computer work good , but for multiple files *.json,
same to me, is worst.
Code: Pascal  [Select][+][-]
  1. {$R *.res}
  2. Var json1:string='';
  3.     boca:integer=00;
  4. begin
  5.   RequireDerivedFormResource:=True;
  6.   Application.Title:='laz-JSON-Viewer';
  7.   Application.Scaled:=True;
  8.   Application.Initialize;
  9.   Application.CreateForm(TfrmMain, frmMain);
  10.   Json1:=paramstr(01);
  11.   boca:=0000;
  12.   if (length(json1)>03) then boca:=pos('*',json1)+001;
  13.   if (boca=01) and (FileExists(json1)) then frmMain.LoadFile(json1) else
  14.   if (boca>01)
  15.   ???
  16.   Application.Run;
  17. end.
  18.  
Do not forget, you move from "private ...procedure LoadFile(const AFilename: UTF8String);  " to " public  procedure LoadFile(const AFilename: UTF8String);     "
 :-X
C:Q1= I do not understand, UTF8String is more-equal with Shortstring?
Why he do not use String ?


« Last Edit: July 03, 2025, 07:54:19 pm by d2010 »

Nicole

  • Hero Member
  • *****
  • Posts: 1303
Re: json goes RichMemo
« Reply #10 on: July 03, 2025, 08:03:14 pm »
Thank you all for those ideas!

@rvk
those units are work in progress since several days. There is one unit for yahoo, one for Alpha Vantage, Figi, ttingo, marketwatch,...

My "one frame does it all" became monstroes before.

However you seem to have golden fingers:

I searched for newsapi and fpc the Google AI already gave me a complete example to retrieve the newsapi.org and filter it's result to a TMemo (without me even asking for it) 

I spent a lot of time there, however it did not bless me with this.
Can you kindly post a copy or let me have the link?

cdbc

  • Hero Member
  • *****
  • Posts: 2617
    • http://www.cdbc.dk
Re: json goes RichMemo
« Reply #11 on: July 03, 2025, 08:04:11 pm »
Hi
@d2010: Well, UTF8String is an 'AnsiString' with its codepage set to CP_UTF8, thus it's allocated on the heap and is managed -- a pointer-type --
Otoh, a 'Shortstring' S is a value-type, i.e.: an array[0..255] of (ansi)char;
Where the S[0] is a char whose ordinal value corresponds to the length of the string (1..255) and the actual string-data start @ S[1]. It's the oldest stringtype in pascal and also the one to use in record-fields. You can also use it across library borders (dll/so).
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE6/QT6 -> FPC Release -> Lazarus Release &  FPC Main -> Lazarus Main

rvk

  • Hero Member
  • *****
  • Posts: 6944
Re: json goes RichMemo
« Reply #12 on: July 03, 2025, 08:16:49 pm »
I searched for newsapi and fpc the Google AI already gave me a complete example to retrieve the newsapi.org and filter it's result to a TMemo (without me even asking for it) 

I spent a lot of time there, however it did not bless me with this.
Can you kindly post a copy or let me have the link?
It was just from a search (see image).
The code it gave me was conceptual so probably doesn't run directly.
But you probably already have similar code.

Besides, you can also use chatgpt, copilot or perplexity AI's to give you more accurate code.

Example (conceptual):
Code: Pascal  [Select][+][-]
  1. uses
  2.   System.SysUtils,
  3.   IdHTTP,
  4.   IdBaseComponent,
  5.   IdComponent,
  6.   IdTCPConnection,
  7.   IdTCPClient,
  8.   IdIOHandler,
  9.   IdSSLOpenSSL,
  10.   IdSSLContext,
  11.   IdMessageClient,
  12.   fcl.json;
  13.  
  14. var
  15.   HTTP: TIdHTTP;
  16.   Response: string;
  17.   JSON: TJSONObject;
  18.   Articles: TJSONArray;
  19.   i: Integer;
  20.   Article: TJSONObject;
  21.   Title: string;
  22.   URL: string;
  23. begin
  24.   HTTP := TIdHTTP.Create(nil);
  25.   try
  26.     // Replace with your API key and desired endpoint
  27.     HTTP.Request.Accept := 'application/json';
  28.     Response := HTTP.Get('https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY');
  29.  
  30.     JSON := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(Response), 0) as TJSONObject;
  31.     if JSON <> nil then
  32.     begin
  33.       Articles := JSON.Get('articles') as TJSONArray;
  34.       if Articles <> nil then
  35.       begin
  36.         for i := 0 to Articles.Count - 1 do
  37.         begin
  38.           Article := Articles.Get(i) as TJSONObject;
  39.           Title := Article.Get('title').Value;
  40.           URL := Article.Get('url').Value;
  41.           // Process the title and URL
  42.           Writeln(Title);
  43.           Writeln(URL);
  44.         end;
  45.       end;
  46.       JSON.Free;
  47.     end;
  48.   finally
  49.     HTTP.Free;
  50.   end;
  51.   ReadLn;
  52. end.

paule32

  • Hero Member
  • *****
  • Posts: 645
  • One in all. But, not all in one.
Re: json goes RichMemo
« Reply #13 on: July 03, 2025, 08:24:06 pm »
wow, 1000 Lines more...

why not working with a Database and holding one JSON structure ?
so, you have multiple Records, and you can template the JSON structure.

It is not a good idea to mix meta data with code data in one source.

So, you have
- a Executable for your business logic
- b Database with your records (which can be more than 10.000 Lines)
- c SQL Queries that can be inject into a) to read b)

SQL Queries can be simple external SQL Files because you give the Text in a Text File.
By doing this, you would realize a very faster performance instead using static JSON and Database SQL Structure's.
MS-IIS - Internet Information Server, Apache, PHP/HTML/CSS, MinGW-32/64 MSys2 GNU C/C++ 13 (-stdc++20), FPC 3.2.2
A Friend in need, is a Friend indeed.

CM630

  • Hero Member
  • *****
  • Posts: 1616
  • Не съм сигурен, че те разбирам.
    • http://sourceforge.net/u/cm630/profile/
Re: json goes RichMemo
« Reply #14 on: July 03, 2025, 10:10:59 pm »
...
There are no open issues regarding TRichmemo that I am aware of....
There is a bug tracker which is aware, I have filed a bug report in January, but nothing seems to be handles in the last 3 years.
« Last Edit: July 04, 2025, 08:04:38 am by CM630 »
Лазар 4,4 32 bit (sometimes 64 bit); FPC3,2,2

 

TinyPortal © 2005-2018