thomaserlang / delphi-json Goto Github PK
View Code? Open in Web Editor NEWJSON parser for Delphi.
JSON parser for Delphi.
Hi for some reason I'm getting unknown field results from this json data: http://qs.quantumsoftware.co.za/tmp/songs.json
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;
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.
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;
Hi. I have problems with compiling for android. Is it normal ?
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.
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.
Integers are handled with AsInteger, but there is no AsDouble property for TdJSON instances.
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.
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?
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": ""
}
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;
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;
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.
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.
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
}
]
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.
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
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
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!"
}
Thanks for sharing. Very interesting
Do you have any example of parsing through an entire hiearchy read via .parsefile and printing this out in a form or back in a .json format?
Best regards
Stephen
How would I go about parsing this: https://umod.org/plugins.json if those numbers under "all" are random?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.