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

ikelaiah iwan.kelaiah at gmail.com
Mon Aug 1 04:24:41 UTC 2022


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.

**Question**

While this works, is there a more concise way than this?
Thank you for your time.


```d
module combinejsonv2;

import std.file;
import std.stdio;
import std.json;
import std.array;
import std.algorithm.searching;

void main()
{
     // can't I use this for JSON array?
     JSONValue jj;

     // create a string opening [ for JSON array
     string stringResult = "[";

     foreach (string filename; dirEntries(".", "*.json", 
SpanMode.shallow))
     {
         // if filename contains 'output' in it, ignore
         if(canFind(filename, "output")) {
             std.stdio.writeln("ignoring: " ~ filename);
             continue;
         }

         // show status to console
         std.stdio.writeln("processing: " ~ filename);

         // read JSON file as string
         string content = std.file.readText(filename);
         // parse as JSON
         JSONValue j = parseJSON(content);

         foreach (JSONValue jsonObject; j.array) {
             // Combine objects from files into a single list of 
JSON object
             // std.stdio.writeln(jsonObject.toPrettyString);
             stringResult ~= jsonObject.toString;
             stringResult ~= ",";
         }
     }

     // create closing ] for the JSON array
     stringResult ~= "]";

     // parse the string as a JSON object
     JSONValue jsonResult = parseJSON(stringResult);

     // write to file
     std.file.write("output-combined.json", 
jsonResult.toPrettyString);
}

```


More information about the Digitalmars-d-learn mailing list