json php error, but json is correct

Asked

Viewed 543 times

0

My php script returns a json, porˆm when js will read json error. erro json

But copying and pasting the same json into a validator (e.g.: https:/jsonlint.com/) claims to be correct.

For those who can help me I thank.

Edit: segue json

{"ArrayTopFiveItens":[{"Cod_Item":"1","Nome_Comercial":"Coca-Cola Lata","Foto":""},{"Cod_Item":"2","Nome_Comercial":"Coca-Cola KS","Foto":""},{"Cod_Item":"3","Nome_Comercial":"Agua com gas","Foto":""},{"Cod_Item":"4","Nome_Comercial":"Cerveja 600 ML","Foto":""},{"Cod_Item":"5","Nome_Comercial":"Cerveja litro","Foto":""}],"ArrayComandas":[{"Cod_Comanda":"1","Descricao":"Comanda","Nome_Interno":"1","Utilizadores":[{"Ref_Comanda":"1","Fechamento_Forcado":0,"ObjPessoa":{"Cod_pessoa":"1","Nome":"Rafael","CPF":"06282724996","Reponsavel_Financeiro":"0","Email":"","Telefone":""}},{"Ref_Comanda":"1","Fechamento_Forcado":0,"ObjPessoa":{"Cod_pessoa":"2","Nome":"Rafael","CPF":"06282724996","Reponsavel_Financeiro":"0","Email":"","Telefone":""}}],"Itens":[],"Requer_Utilizador":"1","Cor":"info","Atualiza_Painel":"0","TotalComanda":0},{"Cod_Comanda":"2","Descricao":"Comanda","Nome_Interno":"2","Utilizadores":[{"Ref_Comanda":"2","Fechamento_Forcado":0,"ObjPessoa":{"Cod_pessoa":"2","Nome":"Rafael","CPF":"06282724996","Reponsavel_Financeiro":"0","Email":"","Telefone":""}}],"Itens":[],"Requer_Utilizador":"1","Cor":"success","Atualiza_Painel":"0","TotalComanda":0},{"Cod_Comanda":"3","Descricao":"Comanda","Nome_Interno":"3","Utilizadores":[{"Ref_Comanda":"3","Fechamento_Forcado":0,"ObjPessoa":{"Cod_pessoa":"3","Nome":"Joao","CPF":"","Reponsavel_Financeiro":"0","Email":"","Telefone":""}}],"Itens":[],"Requer_Utilizador":"1","Cor":"dark","Atualiza_Painel":"0","TotalComanda":0},{"Cod_Comanda":"4","Descricao":"teste","Nome_Interno":"4","Utilizadores":[{"Ref_Comanda":"4","Fechamento_Forcado":0,"ObjPessoa":{"Cod_pessoa":"4","Nome":"Teste a","CPF":"69454976826","Reponsavel_Financeiro":"0","Email":"","Telefone":"47999285532"}}],"Itens":[],"Requer_Utilizador":"1","Cor":"info","Atualiza_Painel":"0","TotalComanda":0},{"Cod_Comanda":"5","Descricao":"wsdf","Nome_Interno":"5","Utilizadores":[{"Ref_Comanda":"5","Fechamento_Forcado":0,"ObjPessoa":{"Cod_pessoa":"4","Nome":"Teste a","CPF":"69454976826","Reponsavel_Financeiro":"0","Email":"","Telefone":"47999285532"}}],"Itens":[],"Requer_Utilizador":"1","Cor":"dark","Atualiza_Painel":"0","TotalComanda":0},{"Cod_Comanda":"6","Descricao":"teste","Nome_Interno":"6","Utilizadores":[{"Ref_Comanda":"6","Fechamento_Forcado":0,"ObjPessoa":{"Cod_pessoa":"4","Nome":"Teste a","CPF":"69454976826","Reponsavel_Financeiro":"0","Email":"","Telefone":"47999285532"}}],"Itens":[],"Requer_Utilizador":"1","Cor":"info","Atualiza_Painel":"0","TotalComanda":0}],"permissaoCLIENT":true,"NomeArquivoImpressao":"","NomeImpressora":"","TemImpressao":false,"ComandaFechada":{"Cod_Comanda":null,"Descricao":"","Nome_Interno":null,"Utilizadores":[],"Itens":[],"Requer_Utilizador":1,"Cor":"primary","Atualiza_Painel":true,"TotalComanda":0},"Cod_Item_Venda_Direta":0,"Nome_Interno_Venda_Direta":" ","Preco_Venda_Venda_Direta":0,"Quantidade_Venda_Direta":0,"Abre_Venda_Direta":0,"DigitoVerificadorAutomatico":"","Alerta":true,"StatusOperacao":true,"MSGOperacao":"","InexistenteException":false}

JS code first part:

  $.post('./assets/classes/Controller.Controller.php', {acao: 'new' ,  Controller: controller , data:data}, function(x){
       VerificaNotificacao("ao Limpar Formulario",x,true);
       popular(x);
       ModalClose();
       FocusCampo('.primeiro');

  });

Function Verification notification

function VerificaNotificacao(acao,json,somenteError){
        var obj = JSON.parse(json);
        DigitoVerificadorAutomatico = obj.DigitoVerificadorAutomatico;
        if(DigitoVerificadorAutomatico == 0){
            $('.dig').attr('readonly','readonly');
        }else{
            $('.dig').removeAttr('readonly');
        }
        if(obj.Alerta === true){
            if(obj.StatusOperacao === true){
                if(!somenteError){
                    Notificacao("Sucesso ","Sucesso "+acao,"success");
                }
                return true;
            }else{
                Notificacao("Ocorreu um erro","Erro "+acao+"\nErro: "+obj.MSGOperacao,'error');
                return false;
            }
        }
  }

error occurs on this line var obj = JSON.parse(json);

Thank you to everyone who helped

  • following photo of validator https://i.stack.Imgur.com/kDPoS.png

  • Can you put the JSON text in the question? ( currently only the image)

  • I put in the post because it exceeds the length of the answer, copied and pasted from my debuger

  • 2

    the guys go negative without even understanding what is happening. Send the js code to evaluate better. Or edit the post with the js code that returns this error.

  • True, I know it’s a well-attended subject, but I searched well before posting. so my system is kind of complex are many code but I’ll try to post the main part of the error

  • the function is not inside the marking

  • Try putting JSON.stringify() in the first part $.post('. /Assets/classes/Controller.Controller.php', {action: 'new' , Controller: controller , data:data}, Function(x){ Verification("to Clear Form",JSON.stringify(x),true);

  • I tried and it didn’t work.

  • Rafael, try it like this: $.post( './assets/classes/Controller.Controller.php', {acao: 'new' , Controller: controller , data:data}, function(x){ .... }, "json");

  • I did what @Everson said and everything went well, but I’m doubtful, because I have other screens that use the same function and there is error that could be ?

  • +1 for question, this is a type of problem that many people have with jQuery and I know it will be useful for future visitors ;D

Show 6 more comments

3 answers

1

The error is related to JSON.parse in your javascript code.

This can happen when trying to parse an invalid JSON, but as in your example JSON is valid, make sure you are not trying to parse an already parsed JSON:

var res = JSON.parse('{"key":"value"}'); // Sucesso, faz o parse JSON de uma string
var res = JSON.parse({"key":"value"}) // Erro, pois o JSON já é um objeto javascript 

In this case, jQuery already returns the answer as a parsed JSON, so it is not necessary to JSON.parse(json);

  • I performed a test, giving Alert in json return and an obj json to compare the difference between the two Function Notification(acao,json,somenteError){ Alert(json); var a = {"firstName":"John", "lastname":"Doe"} ; Alert(a); var obj = JSON.parse(json); } Alert(json) === Generated a String Alert(a); === Generated an Object [Object][Object] I believe json is coming a String itself. (I can’t say if my test is to rule out the possibility that what you said is happening)

  • Dei Alert with typeof and this coming String same json

  • You can try placing the parameter dataType in the ajax of $.post. So you say that the expected return is of the json type. Hence it would look something like this: $.post(url, dados, function() { ... }, 'json');. Further information on https://api.jquery.com/jquery.post/

  • Maybe this can help you https://answall.com/questions/208564/por-qu%C3%AA-o-post-n%C3%A3o-returns-an-object

0

I found characters like r n in your json. Try removing them in php before moving to variable. Suggestion:

$json = preg_replace("/\r\n|\r|\n/", ' ', $json);

I simulated your code by testing only this part with problem, changing where there is r n by /r/n and I have no more error. https://jsfiddle.net/6baw5gqp/

  • I removed r n in jsfiddle(https://jsfiddle.net/6baw5gqp/5/) this passing ok without errors but in my continue giving error with the new json, updated the json of the topic

  • did not understand rafael. You replaced in fiddle the json that was there, so you updated in the topic and again appeared the error??

0


The point is that jQuery specifically already does the "parse" for Json automatically as described in:

The default is "smart guessing", meaning jQuery tries to guess the content of the answer, even more if the Content-type is set to something like application/json (which should help in "divination"), I believe you are using jQuery because of this:

$.post(...

Then it’s not necessary:

var obj = JSON.parse(json);

Just do something like:

var obj = json;

Of course you can force the behavior as text and parse afterwards:

$.post('./assets/classes/Controller.Controller.php', {acao: 'new' ,  Controller: controller , data:data}, function(x){
   VerificaNotificacao("ao Limpar Formulario",x,true);
   popular(x);
   ModalClose();
   FocusCampo('.primeiro');
}, "text"); //Definido como texto

Or force json and remove JSON.parse, thus:

$.post('./assets/classes/Controller.Controller.php', {acao: 'new' ,  Controller: controller , data:data}, function(x){
   VerificaNotificacao("ao Limpar Formulario",x,true);
   popular(x);
   ModalClose();
   FocusCampo('.primeiro');
}, "json"); //Força o proprio jQuery fazer o parse

function VerificaNotificacao(acao,json,somenteError){
    var obj = json;//Sem json parse

    DigitoVerificadorAutomatico = obj.DigitoVerificadorAutomatico;
    if(DigitoVerificadorAutomatico == 0){
        $('.dig').attr('readonly','readonly');
    }else{
        $('.dig').removeAttr('readonly');
    }
    if(obj.Alerta === true){
        if(obj.StatusOperacao === true){
            if(!somenteError){
                Notificacao("Sucesso ","Sucesso "+acao,"success");
            }
            return true;
        }else{
            Notificacao("Ocorreu um erro","Erro "+acao+"\nErro: "+obj.MSGOperacao,'error');
            return false;
        }
    }
}
  • I did what you suggested, no error, but when I will recover one of the data returns Undefined

  • @Rafaelvitordasilva great, we solved the main problem, now this Undefined is another mistake, probably something you did wrong, could say which variable is accusing undefined for me to try to fix?

  • @Rafaelvitordasilva If you can’t see what returned Undefined add this to your code var obj = json; console.log(obj); and then in the browser console you get the answer and send me ;)

  • I did what @Everson said and everything went well, but I’m doubtful, because I have other screens that use the same function and not error that could be ?

  • $.post( './Assets/classes/Controller.Controller.php', {action: 'new' , Controller: controller , data:data}, Function(x){ .... }, "json"); added at the end , "json")

  • @Rafaelvitordasilva is what I said, jQuery tries to make "clever guesswork", even more if the Content-type is set to something like application/json, What Everson said was the same thing I said, force the parameter dataType (of course I suggested using as text to be able to use json.parse), but anyway the whole problem is due to Intelligent Guess of jQuery ;) ... I updated the answer to become canonical https://answall.com/a/209200/3635

  • 1

    I put text as you indicated and I didn’t need to change anything else or for me, your answer was exactly what I needed, Thanks for the help.

  • @Rafaelvitordasilva for nothing, if you can mark as correct I would also be grateful :D, if you do not know how to do this, here is a guide: https://pt.meta.stackoverflow.com/a/1079/3635 See more

Show 3 more comments

Browser other questions tagged

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