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

Christian Köstlin christian.koestlin at gmail.com
Mon Aug 1 07:35:34 UTC 2022


On 2022-08-01 06:24, 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.
> 
> **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);
> }
> 
> ```
An arguably shorter solution (that drops some of your logging) could be:

```d
import std;

void main() {
     dirEntries(".", "*.json", SpanMode.shallow)
         .filter!(f => !f.name.canFind("output"))
         .map!(readText)
         .map!(parseJSON)
         .fold!((result, json) { result ~= json.array; return result; })
         .toPrettyString
         .reverseArgs!(std.file.write)("output-combined.json");
}
```
not sure if you are looking for this style though.


kind regards,
Christian


More information about the Digitalmars-d-learn mailing list