GithubHelp home page GithubHelp logo

delphi-json's People

Contributors

adriaanboshoff avatar anders0nmat avatar darkkeks avatar fabiomux avatar thomaserlang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

delphi-json's Issues

Key improvement

Hi, i just wanted to say, that i love this API.

Besides I added support for fast Path description, idk how to describe it.
I made that instead of this
dJSONObj['items']['part']['snippet']['url'].asString
you can write this
dJSONObj['items|part|snippet|url'].asString

I am not sure if this is useful but it made my life easier.

Access Violation on Parse.

Hi, Is there a reason that this might cause an access violation?
Note: I have changed the object names from TJSON to TdJSON to avoid conflicts with json writers.

function IsValidLicense(const aLicense: string): Boolean;
var
  http: TIdHTTP;
  jdata: TdJSON;
begin
  http := TIdHTTP.Create(nil);
  try
    jdata.Parse(http.Get('http://qs.quantumsoftware.co.za:7777/rsm/license?key=' + aLicense));
    try
      Result := jdata['valid'].AsBoolean;
    finally
      jdata.Free;
    end;
  finally
    http.Free;
  end;
end;

This is the json response:

{
  "valid": true,
  "message": "Product key is valid!"
}

GetJSONByNameOrIndex - do you have an example of how this is used?

I am looking for a way of obtaining a certain ID of a given file. I do not need to parse the entire file, just one of the initial Items.
Do you have a good way of doing this?

Further in the code I stumbled over the function GetJSONByNameOrIndex. Do you have an example on how this can be used?

Thanks in advance

/Stephen

Checking if a field exists

Is it possible to check if a field exists? Like sometimes an api doesn't return a field and it just exists the current method.

TDJson parsing ... Pb

Hi,

i'have a JSON from weather underground like :


{"observations":[{"stationID":"IVENES1","obsTimeUtc":"2020-01-19T10:45:31Z","obsTimeLocal":"2020-01-19 
11:45:31","neighborhood":"Venesmes","softwareType":"EasyWeatherV1.4.4","country":"FR","solarRadiation":94.6,"lon":2.30547237,"realtimeFrequency":null,"
epoch":1579430731,"lat":46.8543663,"uv":0.0,"winddir":35,"humidity":82,"qcStatus":-1,"metric":
{"temp":3,"heatIndex":3,"dewpt":1,"windChill":2,"windSpeed":6,"windGust":7,"pressure":1037.52,"precipRate":0.00,"precipTotal":0.00,"elev":169}}]}

And try to get alls metric fields. So i do ๐Ÿ‘

var
  WX: TDJson;
  observations: TDJson;
  metric: TDJson;
  WXData: TWXDate { TWXData is a record }
begin
   WX := TDJSon.Parse( {MY_JSON_STRING} );

  for observations in WX['observations'] do
  begin
    Self.WXData.stationID:= observations['stationID'].AsString;
  end;

  for metric in WX['observations'] do
  begin
    WXData.temp := metric['temp'].AsDouble; { Unknown field : temp }
  end;

  Self.Memo2.Lines.Add('stationID: ' + Self.WXData.stationID); { ALL is RIGHT }
end;

How to get all the metric field.

Thanks for any help.

Crash on trying to parse 3 items.

So it seems when I try to parse this it works fine but as soon as there are 3 players it just gives me an access violation. Any reason why?

[
  {
    "SteamID": "removed",
    "OwnerSteamID": "0",
    "DisplayName": "removed",
    "Ping": 200,
    "Address": "removed",
    "ConnectedSeconds": 6386,
    "VoiationLevel": 0.0,
    "CurrentLevel": 0.0,
    "UnspentXp": 0.0,
    "Health": 97.70907
  },
  {
    "SteamID": "removed",
    "OwnerSteamID": "0",
    "DisplayName": "removed",
    "Ping": 264,
    "Address": "removed",
    "ConnectedSeconds": 3882,
    "VoiationLevel": 0.0,
    "CurrentLevel": 0.0,
    "UnspentXp": 0.0,
    "Health": 100.0
  }
]

My parse code:

procedure Tfrmmain.GetPlayers(Data: string);
var
  users, user: TJSON;
  item: TListItem;
begin
  users := TJSON.Parse(Data);
  try
    for user in users do
    begin
      item := listViewPlayers.Items.Add;
      item.Caption := user['SteamID'].AsString;
      item.SubItems.Add(user['ConnectedSeconds'].AsString + ' Seconds');
      item.SubItems.Add(user['DisplayName'].AsString);
      item.SubItems.Add(user['Ping'].AsString);
      item.SubItems.Add(user['Address'].AsString);
      item.SubItems.Add(user['Health'].AsString);
    end;

  finally
    users.Free;
  end;
end;

EDIT: Is it possible that the string that it tries to parse is to long?

Unknown Field Result

Hi there Thomas im programming in Firemonkey programming for MultiDevice on Delphi 10.2 Community Edition and trying to parse this http://qs.quantumsoftware.co.za/tmp/songs.json however i keep getting an Unknown Field error.

Here is where the exception is being raised:

function TdJSON.GetJSONByNameOrIndex(const AData: variant): TdJSON;
var
typestring: string;
begin
case VarType(AData) and VarTypeMask of
varString, varUString, varWord, varLongWord:
if not FItems.TryGetValue(AData, result) then
raise EJSONUnknownFieldOrIndex.Create(format('Unknown field: %s', [AData]))
else
exit;
varInteger, varInt64, varSmallint, varShortInt, varByte:
begin
if (FListItems.Count - 1) >= AData then
begin
result := FListItems.items[AData];
exit;
end
else
raise EJSONUnknownFieldOrIndex.Create(format('Unknown index: %d', [AData]));
end;
end;
raise EJSONUnknownFieldOrIndex.Create(format('Unknown field variant type: %s.', [VarTypeAsText(AData)]));
end;

JSON problems

I just check your JSON parser with Delphi using the SAMPLE 2 (with the same data ) and its works FINE.
[
{
"username": "thomas",
"name": "Thomas"
},
{
"username": "kurt",
"name": "Kurt"
},
{
"username": "bent",
"name": "Bent"
}
]

var
users: TJSON;
user: TJSON;
begin
users := TJSON.Parse({JSON_TEXT});
try
for user in users do
begin
writeln(user['username'].AsString);
writeln(user['name'].AsString);
end;
finally
users.Free;
end;
end;

But When I use the JSON parser with FireMonkey and test in an Android deployment -using the same data like before- I have an error "unknow field: username"

I debug both samples and I found this difference :

***** debugging lines, where the ERROR raise *****
case VarType(AData) and VarTypeMask of
varString, varUString, varWord, varLongWord:
if not FItems.TryGetValue(AData, result) then

    raise EJSONUnknownFieldOrIndex.Create(format('Unknown field: %s', [AData]))

  else
    exit;
  • Only Delphi : NO errors and uses SYSTEM.GENERICS.DEFAULT library
  • With Firemonkey : ERROR and uses SYSTEM.variants and SYSTEM

I run this code Thomas wrote and I download the new JSON library :

var
user: TJSON;
s: string;
begin
with TJSON.Parse({JSON DATA}) do
begin
try
showmessage(inttostr(Items.count));
for s in items.Keys do
ShowMessage(s);
finally
Free;
end;
end;
end;

... and did not worked.
But I changed the string taking off the initial and end '[' ']' and
now the new code ,the last one, is working fine, but the example raises an internal code ,not JSON class code like this "Access violation at address 5393dbfa , accessing address 0000000C"

Thanks in advance for your time and help.

Random AV

I'm unsure what I'm doing wrong however I seem to be getting a random access violation when trying to read the following file. Using Rad Studio 10.4.1

File:

{
    "Options": {
        "Modded": true,
        "PluginWatchers": true,
        "DefaultGroups": {
            "Players": "default",
            "Administrators": "admin"
        },
        "WebRequestIP": "0.0.0.0"
    },
    "OxideConsole": {
        "Enabled": true,
        "MinimalistMode": true,
        "ShowStatusBar": true
    }
}

Code Reading it: (Gets Executed on Main Form Create event)

procedure TframeuModOxide.ReaduModConfig;
begin  
  if FileExists(OXIDE_CONFIG) then
  begin
    var jdata := TdJSON.Parse(OXIDE_CONFIG);
    try
      // Causes access violation.....
      if jdata['Options']['Modded'].AsBoolean then
        cbbServerListCategory.ItemIndex := 0
      else
        cbbServerListCategory.ItemIndex := 1;

      swtchPluginWatchers.IsChecked := jdata['Options']['PluginWatchers'].AsBoolean;
    finally
      jdata.Free;
    end;
  end;
end;

Not an issue but need assistance.

Hi, So I've been using your parser for a while now but I seem to be stuck on an issue and I have no idea what wrong.

Current Code: (Delphi FMX)

procedure TfrmMain.GetRustDevblog;
var
  http: TIdHTTP;
  jsonText: string;
  json, blogs, blog: TJSON;
  ListBoxItem: TListBoxItem;
begin
  lstDevBlog.Clear;
  http := TIdHTTP.Create(Self);
  try
    jsonText := http.Get('http://api.facepunch.com/api/public/manifest/?public_key=j0VF6sNnzn9rwt9qTZtI02zTYK8PRdN1');
    http.Free;
  except
    on E: Exception do
      ShowMessage(E.Message);
  end;

  json := TJSON.Parse(jsonText);
  try
    blogs := TJSON.Parse(json['News'].AsString);
    try
      for blog in blogs['Blogs'] do
      begin
        ListBoxItem := TListBoxItem.Create(lstDevBlog);
        ListBoxItem.ItemData.Text := blog['Title'].AsString;
        ListBoxItem.ItemData.Detail := blog['SummaryHtml'].AsString;
        lstDevBlog.AddObject(ListBoxItem);
      end;
    except
      on E: Exception do
        ShowMessage(E.Message);
    end;

  finally
    json.Free;
    blogs.Free;
  end;

end;

I get a Access Violation and it seems to happen after: json := TJSON.Parse(jsonText);

I don't see anything wrong. Is there and easier way I can do this or do you have an idea whats wrong?

I have attached the json response from the api that looks better.

data.txt

Invalid Pointer operation after value access

I just spotted a problem when accessing a item.

Pseudo-Code
fResult: TObjectList<TdJSON>; fYtapi.Get('channels','part=contentDetails',[ 'id=' + fResult[ListBox1.ItemIndex]['id|channelId'].AsString]); // After that call, freeing fResult or calling this line again crashes

Writing to JSON files.

I know this is just a parser and it is really useful and easy to use. If only you can make it so that you can write to the json in such a easy way that would be great.

Handling null value

I have this response from a REST API:

{
   "status": true,
   "result": "OK",
   "json" :  {
	      "last_name": "Wilson"	
	    }
}

That sometimes brings an empty "json" element.. as null:

{
   "status": true,
   "result": "ERROR",
   "json" : null
}

And the code that I use is something like this. Works perfect in the first case, but fails when "json" has a null value.. How can I trap that error? I tried Assigned, nil, VarIsNull, etc but always get a violation.

Must be something simple but escapes me - Thanks for your help and this great utility.

JResp             := TdJSON.Parse(Content);
JResult           := JResp['result'].AsString;

if ( JResp['json'] <> nil ) then begin
      UserLast := JResp['json']['last_name'].AsString;
end;

Best way to parse this?

Sorry I must be annoying with all my questions. What is the best way I can parse this? It's raw data straight from my server. I want to get the Display Names in a combobox

{
  "Message": "[\r\n  {\r\n    \"SteamID\": \"removed\",\r\n    \"OwnerSteamID\": \"0\",\r\n    \"DisplayName\": \"[CS] <Ch@o$> Magician\",\r\n    \"Ping\": 21,\r\n    \"Address\": \"removed\",\r\n    \"ConnectedSeconds\": 13416,\r\n    \"VoiationLevel\": 0.0,\r\n    \"CurrentLevel\": 0.0,\r\n    \"UnspentXp\": 0.0,\r\n    \"Health\": 90.6981354\r\n  },\r\n  {\r\n    \"SteamID\": \"removed\",\r\n    \"OwnerSteamID\": \"0\",\r\n    \"DisplayName\": \"[CS] <Ch@o$> Wolfy\",\r\n    \"Ping\": 36,\r\n    \"Address\": \"remove\",\r\n    \"ConnectedSeconds\": 12310,\r\n    \"VoiationLevel\": 0.0,\r\n    \"CurrentLevel\": 0.0,\r\n    \"UnspentXp\": 0.0,\r\n    \"Health\": 100.0\r\n  },\r\n  {\r\n    \"SteamID\": \"removed\",\r\n    \"OwnerSteamID\": \"0\",\r\n    \"DisplayName\": \"Hellzpower dapubg.com\",\r\n    \"Ping\": 109,\r\n    \"Address\": \"removed\",\r\n    \"ConnectedSeconds\": 8882,\r\n    \"VoiationLevel\": 0.0,\r\n    \"Curr
entLevel\": 0.0,\r\n    \"UnspentXp\": 0.0,\r\n    \"Health\": 80.08678\r\n  }\r\n]",
  "Identifier": 0,
  "Type": "Generic",
  "Stacktrace": ""
}

.AsString returning weird string when converted from integer.

Hi, The "steamid" field used to be a type of string but they changed it and now it's returned as a integer. When using .AsString to get the value it gives the following: "7,65611981130345E16" instead of "76561198113034550"

Json Data:

[
  {
    "steamid": 76561198113034550,
    "group": "Banned",
    "username": "Quantum",
    "notes": "Test Ban",
    "expiry": 1603633669
  }
]

Bug with empty value pair

If I have the following, I get an access violation that I can't properly figure

"Key": {} is the issue.

This is coming from a major financial API that I can't control, no idea why they're bringing blank hashes over.

{
  "QueryResponse":
  {
    "Item":
    [
     {
        "ItemGroupDetail": {},
        "Name":"Advance"
      }
]}}

Taking the ItemGroupDetail out or not having any values after ItemGroupDetail clears the issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.