json_encode - Invalid JSON

Asked

Viewed 723 times

4

I created a PHP code to fetch information from a database (Mysql) and "transform" into JSON. I used the json_encode for such.

The output JSON seemed to be correct, but when I use some JSON validator, it always returns an error Unexpected token.

What most intrigues me is that if I manually type the output JSON into the validator, it works! If I give a Ctrl+C and Ctrl+V, the error occurs.

To check the JSON result: http://devsa.url.ph/? Cod=all

What can it be?

<?php
include('connectdb.php');

$something = $_GET['cod'];
$sqlcode = mysql_query("Select descricao from Produtos Where codigo='$something'");
$sqlcode2 = mysql_query("Select descricao from Produtos");

$jsonObj = array();

if ($something == 'all') {
    while ($result = mysql_fetch_object($sqlcode2)) {
        $jsonObj[] = $result;
    }
} else {
    while ($result = mysql_fetch_object($sqlcode)) {
        $jsonObj[] = $result;
    }
}

$final_res = json_encode($jsonObj);

echo $final_res;
?>
  • Note that there is some character before opening the bracket. Use the directional arrows that you will notice.

1 answer

7


A likely diagnosis may be the type of coding.

To fix this, enter the file type header, leave no character type before and after output, make sure your tag <?php is the first thing in the file and remove the tag ?> end of file, or add a exit;:

header('Content-Type: application/json');
$final_res = json_encode($jsonObj);
echo $final_res;
exit;

Check which the encoding from your database, from the PHP file that is printing the data and from the file that is receiving the data. If possible, put them all in UTF-8 without GOOD english.

Complement:

Resposta vista do wireshark

Note that there are two files with GOOD at the beginning.

the code for php header:

header("Content-Type: application/json; charset=utf-8;");
  • 1

    Great answer! The problem was exactly this "such of GOOD", what I did, was to open the php file in Notepad++, I went to the menu "Format" > "UTF-8 encoding (No GOOD)".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.