Combining JSON arrays into a single JSON array -- better way than this?

frame frame86 at live.com
Mon Aug 1 05:52:36 UTC 2022


On Monday, 1 August 2022 at 04:24:41 UTC, ikelaiah wrote:
> Hi,
>
> I've written a cli tool to merge JSON files (containing JSON 
> array) in the current folder as a single JSON file.
>
> My algorithm:
>
> 1. Create a string to store the output JSON array as a string,
> 2. read each file
> 3. read each object in JSON array from input file
> 4. append the string representation of each JSON object in a 
> string
> 5. Parse the result string as JSON
> 6. Save string representation of point 6 above.

If the JSON files are already parsed, why you stringify and 
reparse it? The assign operator of JSONValue allows it to use it 
as associative or plain array (JSON object / JSON array). Each 
member of such an array is of the same type: JSONValue. So to 
merge an array into another, you can simply iterate over its 
members and assign it into to a target array. To initialize as 
such just use `jsonResult.array = [];`

A plain array should be also mergeable via `jsonResult.array ~= 
j.array` (if `j` really is an array, you need to check the type 
first)


More information about the Digitalmars-d-learn mailing list