I’m using the Class “mysql2json” to make my Json.
<?php
class mysql2json{
static public function getJSON($resultSet,$affectedRecords){
mb_internal_encoding("UTF-8");
$numberRows=0;
$arrfieldName=array();
$i=0;
$json="";
//print("Test");
while ($i < mysql_num_fields($resultSet)) {
$meta = mysql_fetch_field($resultSet, $i);
if (!$meta) {
}else{
$arrfieldName[$i]=$meta->name;
}
$i++;
}
$i=0;
$json="{\n\"data\": [\n";
while($row=mysql_fetch_array($resultSet, MYSQL_NUM)) {
$i++;
//print("Ind ".$i."-$affectedRecords<br>");
$json.="{\n";
for($r=0;$r < count($arrfieldName);$r++) {
$json.="\"$arrfieldName[$r]\" : \"$row[$r]\"";
if($r < count($arrfieldName)-1){
$json.=",\n";
}else{
$json.="\n";
}
}
if($i!=$affectedRecords){
$json.="\n},\n";
}else{
$json.="\n}\n";
}
}
$json.="]\n};";
return $json;
}
}
?>
The problem is I’m getting a not valid JSON error in Xcode (iPhone App) and the JSON validator is saying there is an error on line 11 of the results even though line 11 is blank.
Validator: http://jsonlint.com/
Here is a sample URL.
http://leafseed.com/webservice.php?upc=1116102338
Xcode Error:
2012-01-11 08:55:46.137 GroceryVine[6476:bf03] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=10 \"Garbage after JSON\" UserInfo=0x9bbabc0 {NSLocalizedDescription=Garbage after JSON}
Validator Error
Parse error on line 11:
...." } ]};
--------------------^
Expecting 'EOF', '}', ',', ']'
Any Ideas?
Best Solution
I wouldn’t bother with this class. Just use the native
json_encode()DOCs PHP function as it will give you correctly formatted JSON very easily every time.For example:
A list of other PHP JSON implementations can be found on the json.org website (hint: scroll down).
Direct answer
Looking at your updated question with debug output. Looks like there is an errant semi-colon (
;) in your output.Change your last append from
to
And I think that will fix your issue.