Skip to content

Commit 344e70c

Browse files
committed
convert a csv file to json format
Signed-off-by: rahul <[email protected]>
1 parent db7b165 commit 344e70c

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/FileHandler.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,25 @@ public function searchInCsvFile(string $keyword, string $column, string|null $fo
6767
return $this->search($keyword, $column, $format);
6868
}
6969

70+
/**
71+
* @throws InvalidFileException
72+
*/
7073
public function toArray(): array
7174
{
7275
return iterator_to_array($this->getRows());
7376
}
7477

78+
79+
/**
80+
* @throws InvalidFileException
81+
*/
82+
public function toJson(): string
83+
{
84+
$data = $this->toArray();
85+
86+
return json_encode($data);
87+
}
88+
7589
/**
7690
* @throws InvalidFileException
7791
*/

tests/unit/FileHandlerTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,17 @@ public function toArrayMethodReturnsValidArray()
140140
$this->assertEquals($expected, $data[0]);
141141
}
142142

143+
#[Test]
144+
public function toJsonMethodReturnsValidJsonFormat()
145+
{
146+
$jsonData = $this->fileHandler->open(filename: 'movie.csv')->toJson();
147+
148+
$expectedData = '[{"Film":"Zack and Miri Make a Porno","Genre":"Romance","Lead Studio":"The Weinstein Company","Audience score %":"70","Profitability":"1.747541667","Rotten Tomatoes %":"64","Worldwide Gross":"$41.94 ","Year":"2008"},{"Film":"Youth in Revolt","Genre":"Comedy","Lead Studio":"The Weinstein Company","Audience score %":"52","Profitability":"1.09","Rotten Tomatoes %":"68","Worldwide Gross":"$19.62 ","Year":"2010"},{"Film":"Twilight","Genre":"Romance","Lead Studio":"Independent","Audience score %":"68","Profitability":"6.383363636","Rotten Tomatoes %":"26","Worldwide Gross":"$702.17 ","Year":"2011"}]';
149+
150+
$this->assertJson($jsonData);
151+
$this->assertJsonStringEqualsJsonString($expectedData, $jsonData);
152+
}
153+
143154

144155
#[Test]
145156
public function searchByKeywordAndReturnArray()

0 commit comments

Comments
 (0)