Thursday, December 3, 2020

php/js hack script to merge json files, keying on file name

 I know I "should" be using node for this, but:

Here is a php page that reads a bunch of files (in this case the files are "raw/_KEY_.json") and then prints out a single json object:

<pre><script>const raw = <?
$path = "raw";
$files = array_values(array_diff(scandir($path), array('.', '..')));
$tree = array();
foreach($files as $file){   
    list($key,$rest) = explode(".",$file);
    $tree[$key] = json_decode(file_get_contents("$path/$file"));
}
print json_encode($tree);
?>;
document.write(JSON.stringify(raw,null,' '));</script></pre>
For some reason the PHP version I had didn't seem to have JSON_PRETTY_PRINT defined (or I was doing it wrong) so I duck into js to do the pretty printing of the result... kind of an ObHack, that :-D

No comments:

Post a Comment