2

I created a php code to seek informations on database (mySQL) and "transform" to JSON.

The JSON output seems to be correct, but when use some validator, alway returns error: Unexpected token.

If I manually type the JSON output on validator, it works! If I copy and paste, exception occurs.

For verify the JSON: http://devsa.url.ph/?cod=all

<?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;
?>
Rene Sá
  • 4
  • 3
  • 23
  • 4
    **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Oct 14 '14 at 14:07
  • Some JSON validators require objects only. Try using json_encode with JSON_FORCE_OBJECT – ItalyPaleAle Oct 14 '14 at 14:11
  • (A better way is to wrap your array in an object: $final_res = json_encode(array('result' => $jsonObj)); – ItalyPaleAle Oct 14 '14 at 14:11
  • possible duplicate of [PHP decoding and encoding json with unicode characters](http://stackoverflow.com/questions/7381900/php-decoding-and-encoding-json-with-unicode-characters) – Bogdan Burym Oct 14 '14 at 14:19

2 Answers2

3

You have Byte Order Marks (BOM) at the beginning of your file.

You should save your script without a BOM as this causes your output to be invalid json.

If you look in your developers tools at the exact response, you will see two  sequences at the start before the json starts:


[{"descricao":"Amendoim"},{"descricao":"Cerveja"},{"descricao":"Peixe"}]

You should save your script without a BOM as this causes your output to be invalid json.

jeroen
  • 91,079
  • 21
  • 114
  • 132
1

Your json starts three bytes that represent the BOM for UTF-8

EF BB BF

http://en.wikipedia.org/wiki/Byte_order_mark

Perhaps some parsers don't like those first three bytes