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

ikelaiah iwan.kelaiah at gmail.com
Mon Aug 1 09:01:35 UTC 2022


On Monday, 1 August 2022 at 05:52:36 UTC, frame wrote:

> 
> If the JSON files are already parsed, why you stringify and 
> reparse it?
> 

Because of ...

1. mental block and
2. I didn't know `jsonResult.array = [];`

Many thanks for pointing this out. I tried the following, and 
didn't work, and hence my earlier convoluted approach:

- `JSONValue[] jsonResult;`
- `JSONValue jsonResult = [];`

>
> 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)
> 

Based in your suggestion, the snippet is now more brief.

```d
module combinejsonv3;

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

     void main()
     {
         // merged JSON to be stored here
         JSONValue jsonResult;
         jsonResult.array = [];

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

             // read JSON file as string
             string content = std.file.readText(filename);

             // parse as JSON
             JSONValue j = parseJSON(content);

             // if JSONType is array, merge
             if(j.type == JSONType.array) {
                 // show status to console
                 std.stdio.writeln("processing JSON array from: " 
~ filename);
                 jsonResult.array ~= j.array;
             }
         }

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

Thank you!

-ikel


More information about the Digitalmars-d-learn mailing list