{
"Test":{
"A":{
"ins":{
"type":"pac",
"id":{
"values":{
"test_number":"156764589",
"val":"abcde",
"val_2":"gggg",
"val_3":"jjjj"
},
"verif":{
},
"bool":"INSTR"
}
}
},
"resp":{
"image":"include"
},
"op":{
"id":{
"meth":"def"
}
}
}
}
I am logging a http request been sent & need to remove an element from a TJsonObject
for privacy. However when I attempt to remove key and log it still persists
TJSONObject *obj = (TJSONObject*) TJSONObject::ParseJSONValue(TEncoding::UTF8->GetString(id_http_wrap.msg));
obj->RemovePair("Test.A.ins.type.id.values.test_number");
CodePudding user response:
This should do the trick:
implementation
uses
System.IOUtils, System.JSON;
procedure DoSomeJSONStuff;
var
jsonstr: string;
jo, jochild: TJSONObject;
begin
jsonstr := TFile.ReadAllText('C:\Temp\example.json', TEncoding.UTF8);
jo := TJSONObject.ParseJSONValue(jsonstr) as TJSONObject;
if (jo <> nil) then begin
try
jochild := ((((jo.GetValue('Test') as TJSONObject).GetValue('A') as TJSONObject).GetValue('ins') as TJSONObject).GetValue('id') as TJSONObject).GetValue('values') as TJSONObject;
jochild.RemovePair('test_number');
TFile.WriteAllText('C:\Temp\example_changed.json', jo.ToString, TEncoding.UTF8);
finally
jo.Free;
end;
end;
end;
Keep in mind, that TFile.ReadAllText and WriteAllText with UTF-8 encoding is actually UTF-8-BOM.
Of course, you can format the code better.
CodePudding user response:
First, your path is wrong. type
is not in the path down to test_number
. The correct one would have been:
obj->RemovePair("Test.A.ins.id.values.test_number");
But as far as I know, that can't be parsed by RemovePair
. You'll have to use FindValue
:
// Cast helper:
TJSONObject* ToTJSONObject(TJSONValue* v) {
if(!v) throw Exception("TJSONValue* == nullptr");
return static_cast<TJSONObject*>(v);
}
auto obj = ToTJSONObject(TJSONObject::ParseJSONValue(...));
ToTJSONObject(obj->FindValue("Test.A.ins.id.values"))->RemovePair("test_number");