How to solve JSON.parse problem using Ionic and Angularjs

Asked

Viewed 937 times

1

I have the following error to follow and can not solve:

Error:

Uncaught SyntaxError: Unexpected token ] in JSON at position 142
at JSON.parse (<anonymous>)
at XMLHttpRequest.xmlhttp.onreadystatechange (forma_pag_cad_controller.js:24)

The string is this result:

{"nome":"Dinheiro"}{"nome":"Cheque"}{"nome":"Cart\u00e3o - Cr\u00e9dito  - VR Benef\u00edcios"}{"nome":"Cart\u00e3o Aura - Cr\u00e9dito"}

My code:

// LISTA FORMAS DE PAGAMENTO    
    $scope.formapag = [];

    $scope.getformaspag = function () {
        $scope.formapag = [];
        $ionicLoading.show();       
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var responseishere = xmlhttp.responseText;
                if (responseishere == "error") {
                    $scope.nothing = 1;
                    $ionicLoading.hide();
                    $scope.$broadcast('scroll.refreshComplete');
                } else {
                    $ionicLoading.hide();
                    var myobj = JSON.parse(responseishere);
                    for (var i = 0; i < myobj.length; i++) {
                        $scope.formapag.push(myobj[i]);
                    }
                    $scope.$broadcast('scroll.refreshComplete');
                }
            }
        };

        xmlhttp.open("GET", "http://vovocooks.com.br/admin/apis/vovo/cadastro_vovo/lista_formPag.php", true);
        xmlhttp.send();
    }
    $scope.getformaspag();

I have changed the Json format, but still the error.

Does anyone know what it can be?

UPDATE: Follow my PHP:

    <?php


header('Content-type: application/json; charset=utf-32"');
header('Access-Control-Allow-Origin: *');

include 'database.php';

//$cod_fornecedor=$_GET['cod_fornecedor'];


$query="SELECT
   nome
FROM
   formas_pagamento
ORDER BY
   cod_forma_pagamento ASC";


$result=$con->query($query);

$row_cnt = mysqli_num_rows($result);
if ($result->num_rows > 0) 
{
    $count=0;
    echo "[";
    while($row = $result->fetch_assoc()) 
    {
            $count++;
            echo json_encode($row);

            if($count!=$row_cnt)
            {
                    echo ",";
            }


    }
    echo "]";
}
else
{
echo "error";
}

?>
  • 1

    Edit your question and ask string of json who’s trying to parse

2 answers

3

The problem must be the format of your JSON file is wrong.

When validating through the website https://jsonformatter.curiousconcept.com/, the error found is with regards to comma and simple quotes at the end of the file, the correct json should look like this.

[{"nome":"Dinheiro"},{"nome":"Cheque"},{"nome":"Cart\u00e3o - Cr\u00e9dito  - VR Benef\u00edcios"},{"nome":"Cart\u00e3o Aura - Cr\u00e9dito"}]

Change the JSON file, this should solve.

1


Its JSON format is incorrect, but there is also a large failure point there, if one of these calls to the function json_encode fail within your while loop, your program will generate an inconsistent string as well.

In addition, the function json_encode has a high cost for performance of its application, it is best to perform it only once.

NOTE: Using once will only reduce CPU consumption for processing but it will increase memory usage. Use inside a loop as is being made will use more CPU and less memory but it is more likely syntax failure.

The safest solution is to accumulate the results in an array and then finally perform the json_encode only once with the result and then printing the data in a valid json format generated by the native function itself.

<?php


header('Content-type: application/json; charset=utf-32"');
header('Access-Control-Allow-Origin: *');

include 'database.php';

/*** (...) ***/

$row_cnt = mysqli_num_rows($result);
if ($result->num_rows > 0) 
{
    //$count=0;
    $dados = array();
    //echo "[";
    while($row = $result->fetch_assoc()) 
    {
        array_push($dados,$row);
         /* $count++;
            echo json_encode($row);

            if($count!=$row_cnt)
            {
                    echo ",";
            }
        */

    }
    //echo "]";
    $jsonstr = json_encode($dados);
    //Irá retornar nulo se falhar
    if (!$jsonstr) {
            switch (json_last_error()) {
                case JSON_ERROR_NONE:
                    $msgError = ' - No errors';
                    break;
                case JSON_ERROR_DEPTH:
                    $msgError = ' - Maximum stack depth exceeded';
                    break;
                case JSON_ERROR_STATE_MISMATCH:
                    $msgError = ' - Underflow or the modes mismatch';
                    break;
                case JSON_ERROR_CTRL_CHAR:
                    $msgError = ' - Unexpected control character found';
                    break;
                case JSON_ERROR_SYNTAX:
                    $msgError = ' - Syntax error, malformed JSON';
                    break;
                case JSON_ERROR_UTF8:
                    $msgError = ' - Malformed UTF-8 characters, possibly incorrectly encoded';
//                    var_dump($obj);
                    break;
                default:
                    $msgError = ' - Unknown error';
                    break;
            }
            throw new Exception($msgError, json_last_error());
        } else {
            echo $jsonstr;
        }
}
else
{
echo "[]"; //Use um array vazio para que seu resultado seja mais coeso entre o erro e um resultado vazio. Valide no javascript usando o ".length" do retorno.
}

?>

Browser other questions tagged

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