How to solve JSON.parse problem using Ionic and AngularJS

1

I have the following error 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 already changed the Json format, but continue with 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";
}

?>
    
asked by anonymous 10.02.2017 / 13:10

2 answers

1

Your JSON format is incorrect, but there is also a big breakpoint there, if one of these calls to the function json_encode fails within your while loop, your program will generate an inconsistent string as well.

In addition, the json_encode function has high performance cost of your application, it is best to do it only once .

  

NOTE: One-time use will only reduce CPU consumption for processing   but will increase memory usage. Use within a loop as it is   being done will use more CPU and less memory but it is more likely   of syntax failures.

The safest solution is to accumulate the results in an array and then finally do 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.
}

?>
    
18.04.2017 / 14:45
3

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

When you validate through link , the error found is with respect to the comma and single quotation marks at the end of the file, the correct json should be this way.

[{"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.

    
10.02.2017 / 13:21