//function to implode nested arrays
function multiImplode($array) {
$ret = '';
$glue = ', ';
if(is_array($array)){
foreach ($array as $item) {
if (is_array($item)) {
$ret .= multiImplode($item, $glue) . $glue;
} else {
$ret .= $item . $glue;
}
}
}
$ret = substr($ret, 0, 0-strlen($glue));
return $ret;
}
//function to check if a value is an array or missing
//implodes arrays or returns null
function helperNull ($val){
if(is_array($val)){$val = multiImplode($val);}
if(!$val || $val == ""){
$val = "null";
}
$connectionString = "host=localhost port=5432 dbname=JSON user=username password=somepassword";
$dbConnection = pg_connect($connectionString);
$val = pg_escape_string($dbConnection, $val);
return $val;
}
//read in the file one line at a time. In my case each line was an individual JSON record.
$file_handle = fopen("my_file.json", "r");
//insert processed JSON into a postgres database. From here it is easy to export from postgres into csv or whatever.
while (!feof($file_handle)) {
$line = fgets($file_handle);
$vals = json_decode($line,true);
$connectionString = "host=localhost port=5432 dbname=JSON user=username password=somepassword";
$dbConnection = pg_connect($connectionString)or die('fail');
pg_query("INSERT INTO \"TABLE_1\"(
\"JSON_TOP_LEVEL_1\" ,
\"JSON_TOP_LEVEL_1.NEXT_LEVEL\" ,
\"JSON_TOP_LEVEL_2\" )
VALUES ('".helperNull($vals['JSON_TOP_LEVEL_1'])."',
'".helperNull($vals['JSON_TOP_LEVEL_1']['NEXT_LEVEL'])."',
'".helperNull($vals['JSON_TOP_LEVEL_2'])."');");
}
fclose($file_handle);