-2

I have a json file in which I am storing array of json objects. I am using 'file_get_contents()' to read data, the data read is in the form of string. I am actually returning the data and in the front-end js fetches json data. But I used json_encode() and returned the data. Even then it is returning a string(in json format) instead of json data. Can anyone help me out

My php code

$response = '[';
$date = date('Y-m-d', strtotime($date));
$file = file_get_contents("uploads/sample.json");
$file = str_split($file, strlen($file)-2)[0];
if ($file === '') {
  self::json_respond('', 'Nothing is uploaded on '. date("Y-m-d"));
}
$response .= $file.']';
return json_encode($response);

My json file is

{ "name": "sample.css", "file_path": "uploads/sample.css","date_uploaded":  "2018-07-10" }
{ "name": "simple.mp4", "file_path": "uploads/video1.mp4","date_uploaded": "2018-07-10" }
{ "name": "cat.jpeg", "file_path": "uploads/image.jpeg","date_uploaded": "2018-07-11" },

But is is jsut printing a json string when I do console.log(response) instead of printing the data in json

rammanoj
  • 479
  • 8
  • 26
  • Show us your JSON and your code. – Script47 Jul 11 '18 at 12:04
  • Please go read [ask] and [mcve], and then edit your question accordingly. – CBroe Jul 11 '18 at 12:04
  • 1
    Sounds like you double encode.. file_get_contents reads a string so you use json_encode on a string which causes a double encoded string – Nitro.de Jul 11 '18 at 12:04
  • Show your code please – Saclt7 Jul 11 '18 at 12:06
  • I guess I explained the question in better manner. So, I guess -1 can be removed ?? – rammanoj Jul 11 '18 at 12:14
  • 1
    You are doing this wrong from the very get-go, by providing part of the JSON syntax yourself in “text form”, appending the [ and ] yourself. You should always work on the _decoded_ data structures only, and re-encode them after you are done. _“My json file is”_ - that is not valid JSON, as long as the outer [...] are missing. Those should be part of that file itself already, and not be added on later. _“I have a json file in which I am storing array of json objects”_ - no, you are not - not with what you have shown as the current file content. – CBroe Jul 11 '18 at 12:18

1 Answers1

0

Parse the data with JSON.parse()