Skip to content

Commit b2d6973

Browse files
authored
set expected json format (#34)
Signed-off-by: rahul <[email protected]>
1 parent 37069c6 commit b2d6973

File tree

2 files changed

+70
-3
lines changed

2 files changed

+70
-3
lines changed

bin/view-json

+32
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,38 @@ $command = (new SingleCommandApplication())
5050
);
5151
} catch (FileHandlerException) {
5252
$io->error('invalid json file');
53+
$io->writeln(
54+
'
55+
Expected Format
56+
=======================================
57+
58+
[
59+
60+
{
61+
"title": "The Catcher in the Rye",
62+
"author": "J.D. Salinger",
63+
"published_year": 1951
64+
},
65+
{
66+
"title": "To Kill a Mockingbird",
67+
"author": "Harper Lee",
68+
"published_year": 1960
69+
},
70+
{
71+
"title": "1984",
72+
"author": "George Orwell",
73+
"published_year": 1949
74+
}
75+
76+
]
77+
78+
79+
80+
81+
=======================================
82+
83+
'
84+
);
5385
return Command::FAILURE;
5486
}
5587

src/JsonFileHandler.php

+38-3
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,14 @@ private function getRows(
5050
throw new FileHandlerException("{$filename} is not valid");
5151
}
5252

53-
$contents = json_decode($jsonContents, true);
54-
if (!$contents || json_last_error() !== JSON_ERROR_NONE) {
53+
54+
if (!$contents = $this->isValidJson($jsonContents)) {
5555
throw new FileHandlerException(json_last_error_msg());
5656
}
5757

58+
5859
$count = 0;
59-
$headers = array_keys(reset($contents));
60+
$headers = array_keys($contents[0]);
6061
$indices = is_array($hideColumns) ? $this->setColumnsToHide($headers, $hideColumns) : [];
6162
foreach ($contents as $content) {
6263
if (!empty($indices)) {
@@ -71,4 +72,38 @@ private function getRows(
7172
}
7273
}
7374
}
75+
76+
/**
77+
* @param string $jsonData
78+
* @return array<int,array<string,string>>|false
79+
*/
80+
private function isValidJson(string $jsonData): array|false
81+
{
82+
$data = json_decode($jsonData, true);
83+
84+
if (json_last_error() !== JSON_ERROR_NONE) {
85+
return false;
86+
}
87+
88+
89+
if (!is_array($data)) {
90+
return false;
91+
}
92+
93+
if (!isset($data[0]) || !is_array($data[0])) {
94+
return false;
95+
}
96+
97+
$firstArrayKeys = array_keys($data[0]);
98+
99+
foreach ($data as $item) {
100+
$currentArrayKeys = array_keys($item);
101+
102+
if ($firstArrayKeys !== $currentArrayKeys) {
103+
return false;
104+
}
105+
}
106+
107+
return $data;
108+
}
74109
}

0 commit comments

Comments
 (0)