0

I want to add Data before the array and it is written into the converted json. I have checked that there are no errors when converting, but why isn't there?

This the code

$response = array();
while($row =mysqli_fetch_assoc($result))
{
    $response[] = $row;
}
echo json_encode($response);
    //write to json file
$fp = fopen('op.json', 'w');
fwrite($fp, json_encode('{"Data":', $response), '}');// JSON_PRETTY_PRINT
fclose($fp);

Previous results like this

[
  {
    "id": "6",
    "name": "kiko",
    "score": "999"
  },
  {
    "id": "9",
    "name": "johyn",
    "score": "88"
  },
  {
    "id": "12",
    "name": "aaaani",
    "score": "99"
  }
]

I want the results like this

{
  "Data": [
    {
      "id": "6",
      "name": "kiko",
      "score": "999"
    },
    {
      "id": "9",
      "name": "johyn",
      "score": "88"
    },
    {
      "id": "12",
      "name": "aaaani",
      "score": "99"
    }
  ]
}
2
  • fwrite($fp, '{"Data":' . json_encode($response). '}'); Commented Aug 14, 2018 at 16:47
  • You can also replace the loop and mysqli_fetch_assoc() with mysqli_fetch_all() Commented Aug 14, 2018 at 16:51

2 Answers 2

2

json_encode() encodes an array or object to a JSON String, so make the parameter an array and it will work

fwrite($fp, json_encode(["Data" => $response]);

Or to get JSON_PRETTY_PRINT

fwrite($fp, json_encode(["Data" => $response], JSON_PRETTY_PRINT);
Sign up to request clarification or add additional context in comments.

Comments

1

Rather than trying to code the JSON and then json_encode() it you can use an array to generate the desired output:

$response = array();
while($row =mysqli_fetch_assoc($result))
{
    $response[] = $row;
}
echo json_encode($response);
    //write to json file
$fp = fopen('op.json', 'w');
fwrite($fp, json_encode(array('Data' => $response), JSON_PRETTY_PRINT)); // JSON_PRETTY_PRINT
fclose($fp);

In addition, json_encode() has the ability to pretty print the json by supplying the second parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.