Link to home
Start Free TrialLog in
Avatar of PeterDelphin
PeterDelphin

asked on

How to extract only a specific value from a local JSON file?

I have a file info.json which contains only this code:

{"personal": {"path": "C:\\My Directory", "honk": 82641923}}

Open in new window


In Delphi XE7, using a JSON library, which is the most simple way to extract the path value, i.e. C:\My Directory?
ASKER CERTIFIED SOLUTION
Avatar of jimyX
jimyX

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jimyX
jimyX

Simpler than that could be:
function ParseJsonStr(jStr: String): String;
var
  jObj: TJSONObject;
  jVal: TJSONValue;
begin
  Result:= '';
  jObj := TJSONObject.ParseJSONValue(jStr) as TJSONObject;
  try
    jVal:= jObj.Get(0).JsonValue;
    Result:= TJSONObject(jVal).Get(0).JsonValue.Value;
  finally
    jObj.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Text:= ParseJsonStr('{"personal": {"path": "C:\\My Directory", "honk": 82641923}}'); // or pass the positions as params ", 0, 0"
end;

Open in new window

Avatar of PeterDelphin

ASKER

Delphi XE7 Compiler says:

[dcc32 Error] MainForm.pas(453): E2003 Undeclared identifier: 'TJSONObject'

Open in new window

DElphi XE7 needs System.JSON in uses clause.
In the second example you are iterating true the parts of the JSON object by using the ordinal value (0).

But the parts could also be in a different order. Is it possible to parse the JSON object by looking specifically for a pair where the name is "path" and then just extract the value of this pair?
uses data.dbxjson;
To use the second example the order must always be the same, otherwise use the first example.
When using data.dbxjson instead of System.JSON then the DelphiXE7 compiler says:

[dcc32 Error] MainForm.pas(454): E2003 Undeclared identifier: 'TJSONObject'
I do not have XE7. If System.JSON works then System.JSON is the unit to use.

Seems data.dbxjson has been changed from previous versions.
Great!