Skip to content

Commit d567361

Browse files
authored
Merge pull request #2 from martinsustek/json2csv-data-unification
Json2csv data unification
2 parents 16c9376 + 73870be commit d567361

File tree

4 files changed

+45
-2
lines changed

4 files changed

+45
-2
lines changed

src/File/Json.php

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,28 @@ class Json extends AbstractFile
1616
*/
1717
public function convert() : string
1818
{
19-
return $this->toCsvString(array_map(function ($d) {
19+
$data_decoded = json_decode($this->data, true);
20+
$data_flattened = array_map(function ($d) {
2021
return $this->flatten($d);
21-
}, json_decode($this->data, true)));
22+
}, $data_decoded);
23+
24+
$keys = [];
25+
foreach ($data_flattened as $entry_flattened) {
26+
foreach ($entry_flattened as $key => $value) {
27+
$keys[$key] = true;
28+
}
29+
}
30+
31+
$data_unified = [];
32+
foreach ($data_flattened as $entry_flattened) {
33+
$entry_unified = [];
34+
foreach ($keys as $key => $foo) {
35+
$entry_unified[$key] = array_key_exists($key, $entry_flattened) ? $entry_flattened[$key] : null;
36+
}
37+
$data_unified[] = $entry_unified;
38+
}
39+
40+
return $this->toCsvString($data_unified);
2241
}
2342

2443
/**

tests/JsonTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ public function testConversionAndDownload()
4545
$this->expectOutputRegex('/Turkey,"Republic of Turkey",Türkiye,783562,39,35\\n/');
4646
}
4747

48+
/**
49+
* @group json-conversion-test
50+
*/
51+
public function testConversionDynamicFormat()
52+
{
53+
$json = new Json(__DIR__ . '/data/dynamicFormat.json');
54+
$result = ($json->convert());
55+
$this->assertEquals(file_get_contents(__DIR__ . '/data/dynamicFormatResult.csv'), $result);
56+
}
57+
58+
4859
/**
4960
* @return \OzdemirBurak\JsonCsv\File\Json
5061
*/

tests/data/dynamicFormat.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[
2+
{
3+
"x": 0,
4+
"y": 1
5+
},
6+
{
7+
"y": 0,
8+
"z": 0
9+
}
10+
]

tests/data/dynamicFormatResult.csv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
x,y,z
2+
0,1,
3+
,0,0

0 commit comments

Comments
 (0)