ColdZer0 ColdZer0 - 5 months ago 108
JSON Question

How to parse json files using ISuperObject in Delphi 10

I'm trying to parse a JSON file using ISuperObject. My JSON file looks like this:

{"status": "ok", "follows": {"count": 868, "page_info": {"has_previous_page": false, "start_cursor": null, "end_cursor": "SbXc6VJsoeTs", "has_next_page": true}, "nodes": [{"username": "username1", "requested_by_viewer": false, "followed_by_viewer": true, "profile_pic_url": "URL link", "full_name": "name", "is_verified": false, "id": "ID"}, {"username": "username2", "requested_by_viewer": false, "followed_by_viewer": true, "profile_pic_url": "URL link", "full_name": "username2", "is_verified": false, "id": "ID"}, {"username": "_username3", ...]}


I want all of the
username
values to be listed in a Memo.

Here is what I have tried:

var
json : ISuperObject;
row_item : ISuperObject;
begin
json := TSuperObject.ParseFile('C:\json.txt', TRUE);
for row_item in json['nodes'] do
begin
Memo1.Lines.Add(elements_itemS['usernames']);
end;
end;


I get an Access Violation on the
for
loop. Any ideas?

Answer

The code should look more like this instead:

var
  json         : ISuperObject;
  node         : ISuperObject;
  item         : IMember;
begin
  json := TSuperObject.ParseFile('C:\json.txt', TRUE); 
  for item in json.O['follows'].A['nodes'] do 
  begin
    node := item.AsObject;
    Memo1.Lines.Add(node.S['username']); 
  end;
end;

Or this:

var
  json         : ISuperObject;
  node         : ISuperObject;
  item         : IMember;
begin
  json := TSuperObject.ParseFile('C:\json.txt', TRUE); 
  for item in json['follows.nodes'].AsArray do 
  begin
    node := item.AsObject;
    Memo1.Lines.Add(node.S['username']); 
  end;
end;