logo
down
shadow

How to sort a TJSONArray in delphi


How to sort a TJSONArray in delphi

By : Zied Saïdi
Date : November 27 2020, 05:23 PM
Does that help I ran into this problem a while back. I didn't find any methods that could do the sorting so ended up building my own:
code :
procedure SortJsonArray(aJsonArray: TJsonArray)
var
  cntr: Integer;
  elementList: TList<TJSONValue>;
begin
  // Sort the elements. We have to sort them because they change constantly
  elementList := TList<TJSONValue>.Create;
  try
    // Get the elements
    for cntr := 0 to aJsonArray.Count - 1 do
      elementList.Add(aJsonArray.Items[cntr]);
    elementList.Sort(TComparer<TJSONValue>.Construct(
        function(const Left, Right: TJSONValue): Integer
        var
          leftObject: TJSONObject;
          rightObject: TJSONObject;
        begin            
          // You should do some error checking here and not just cast blindly
          leftObject := TJSONObject(Left);
          rightObject := TJSONObject(Right);
          // Compare here. I am just comparing the ToStrings but you will probably
          // want to compare something else.
          Result := 
              TComparer<string>.Default.Compare(leftObject.ToString, rightObject.ToString);
        end));
    aJsonArray.SetElements(elementList);
  except
    on E: Exception do
    begin
      // We only free the element list when there is an exception because SetElements 
      // takes ownership of the list.
      elementList.Free;
      raise;
    end;
  end;
end;


Share : facebook icon twitter icon
Delphi TJSONArray.ToBytes Access violation - Is it

Delphi TJSONArray.ToBytes Access violation - Is it


By : Mary Beel
Date : March 29 2020, 07:55 AM
This might help you Yes, your use of SizeOf() is wrong. iCJSONCallData is an object, so SizeOf(iCJSONCallData) is effectively the same as SizeOf(Pointer), which is 4 on 32bit and 8 on 64bit.
You need to use the TJSONArray.EstimatedByteSize() method instead:
code :
SetLength(vJSONCallDataBytes, iCJSONCallData.EstimatedByteSize);
vCount := iCJSONCallData.ToBytes(vJSONCallDataBytes, 0);
Find Value Type of a JSONValue (TJSONArray or TJSONObject)

Find Value Type of a JSONValue (TJSONArray or TJSONObject)


By : haaapppy
Date : March 29 2020, 07:55 AM
Does that help I would like to do this with the standard Library in Delphi XE8 , You could use the is operator:
code :
if Assigned(JSONValue) then
begin
  if JSONValue is TJSONArray then
    ProcessArrayResponse(TJSONArray(JSONValue))
  else if JSONValue is TJSONObject then
    ProcessObjectResponse(TJSONObject(JSONValue));
end;
type
  JsonValueType = (jsArray, jsObject, ...);

function GetJsonValueType(JSONValue: TJSONValue): JsonValueType;
begin
  if JSONValue is TJSONArray then Exit(jsArray);
  if JSONValue is TJSONObjct then Exit(jsObject);
  ...
end;

...

if Assigned(JSONValue) then
begin
  case GetJsonValueType(JSONValue) of
    jsArray  : ProcessArrayResponse(TJSONArray(JSONValue));
    jsObject : ProcessObjectResponse(TJSONObject(JSONValue));
  end;
end;
type
  JsonValueType = (jsArray, jsObject, ...);

var
  JsonValueTypes: TDictionary<String, JsonValueType>;

...

if Assigned(JSONValue) then
begin
  case JsonValueTypes[JSONValue.ClassName] of
    jsArray  : ProcessArrayResponse(TJSONArray(JSONValue));
    jsObject : ProcessObjectResponse(TJSONObject(JSONValue));
  end;
end;

...

initialization
  JsonValueTypes := TDictionary<String, JsonValueType>.Create;
  JsonValueTypes.Add('TSONArray', jsArray);
  JsonValueTypes.Add('TSONObject', jsObject);
  ...
finalization
  JsonValueTypes.Free;
Delphi - How do I create a TJSONArray from a array of strings?

Delphi - How do I create a TJSONArray from a array of strings?


By : Colin Lim
Date : March 29 2020, 07:55 AM
I wish this help you You need to construct an empty TJSONArray object first, and then Add() the individual strings values to it. For example:
code :
var
  arr: array of string;
  JSONObj: TJSONObject;
  response_faults: TJSONArray;
  I: Integer;
begin
  arr := ... ; // '001', '002', '005', '009', ...
  JSONObj := TJSONObject.Create;
  try
    response_faults := TJSONArray.Create;
    try
      for I := Low(arr) to High(arr) do begin
        response_faults.Add(arr[I]);
      end;
      JSONObj.AddPair('Events', response_faults);
    except
      response_faults.Free;
      raise;
    end;
    // use JSONObj as needed...
  finally
    JSONObj.Free;
  end;
end;
Update TJSONArray

Update TJSONArray


By : Danny Darwin
Date : March 29 2020, 07:55 AM
help you fix your problem Unfortunately, TJSONArray does not natively allow you to REPLACE existing elements with new values (Why? Who knows). All you can do is ADD and REMOVE elements, and ENUMERATE elements.
Since your array holds TJSONObject instances, to replace such an element with a new object, you will have to either:
Do I need to free instance of TJSONArray

Do I need to free instance of TJSONArray


By : esz
Date : March 29 2020, 07:55 AM
With these it helps It depends on which platform you are running on.
If your app is running on a non-ARC platform, such as Windows or OSX, then YES, you need to manually free the TJSONArray when you are done using it, or else it will be leaked.
Related Posts Related Posts :
  • how to write r.headers from different urls into one json?
  • Parsing JSON concurrently - panic of runtime error (decoding related)
  • How to fix "Subscript out of range" error in XML HTTP Request
  • Splitting nested arrays as separate entities
  • Trying to parse the JSON and create an extracted JSON
  • NiFi JoltTransformJson outputs only first record
  • Dynamic (But known as another key value) JSON Decoding with Swift Decodable
  • How to use map on json response returned by a REST API with ReactJs
  • How to read a file line by line and then output all lines compounded with sth in jq?
  • java.lang.RuntimeException: Failed : HTTP error code : 400 : Bad Request
  • How to check jq result is null or not?
  • CloudFormation - How to use Sub intrinsic function?
  • VBA: Nested JSON Object Structure for UK Bank Holidays - Run Time Errors 13, 438 and 449
  • JasperReports. Using value from parent json in child table
  • Output key value pairs as JSON from T-SQL query
  • Getting key value pairs with linux server
  • Modifying settings.json in vscode to add shell escape flag to pdflatex in latex workshop
  • Unable to render data into grid column using JSON results
  • JSON decode failed
  • How to remove brakets on Json respone
  • How to parse JSON-input
  • JSON syntax for getting personal query ID
  • detecting 400 response without JSON response
  • Newtonsoft deserializing Json incorrectly
  • Getting _jsonparsefailure with valid json in logstash
  • How to send Map as String in POST request in flutter?
  • Difficulty fetching json data from API using Angular
  • Reading JSON data for my select query in SQL Server
  • AWS CloudFormation Template (JSON) to Create EC2 - Unexpected Error
  • How to concat multiple fields to same line with jq
  • Issue sending POST request from Swift
  • Storing JSON in BigQuery
  • How to get the value of a key in a JSON?
  • How to validate JSON input in Go
  • Extracting specific and latest data from http webserver using golang
  • Incorrect type. Expected "object"
  • json_to_record with embedded encoded json in PostgreSQL >= 10
  • Nested json extract from powershell
  • Parsing Json using Golang
  • Type 'number' is not assignable to type 'string'. How to cast number to string
  • kubectl - format the resource quota values in json format
  • Initializing and inserting nested JSON data in Golang?
  • Open JSON files in PhpStorm built-in web server
  • Extract Badge ID from JSON in .gitlab-ci.yml
  • Sharing Json Schema files among projects with versioning
  • Export Json data to an excel file using Angular 4
  • Return an empty array instead of null with golang for json return with gin
  • can Kafka connect value conveter (JSONConverter) can be used to convert GPB?
  • read json and access multiple keys
  • Spark How to get number of Keys changed in two JSONS in Scala?
  • Break JSON in pager "less"
  • How to filter Map in Flutter?
  • Convert hashmap to simple object in Groovy
  • Not extracting json properly using json4s
  • How do I display JSON data in my tableView when objects have the same value?
  • Where I can parse IoT data in Azure so I can afterwards save it to SQL DB
  • How to unmarshal this json string
  • What's wrong with my JSON?
  • JSON parsing problem in BlackBerry
  • GWT: How can I use JsonpRequestBuilder to handle a Json response of a list
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org