Json.parse does not convert to array

Asked

Viewed 373 times

0

Hello, I am a complete amateur in php and javascript and after a month of fighting with two languages I had never touched got here.

I am trying to pass a JSON from a request back to array in my javascript, but when I use parse and print the typeof variable in the console it continues as string and not array. I will leave below the codes and what appeared on the console, along with more information.

PHP code:

<?php

    include("conexao_postgres.php");

    $ano_base = $_POST["ano_ref"];

    $sql = "SELECT * FROM public.parametros_estaduais WHERE ano_base = $ano_base";
    $resultado = pg_query($dbconn, $sql);
    $resultado_array = pg_fetch_row($resultado);

    echo json_encode($resultado_array, JSON_NUMERIC_CHECK);
?>

To speed up and facilitate, I replicated the query with the test I’m doing in the main code to know faster what is happening in PHP. What comes from echo is that from here:

JSON>> [2016,0.02,347.58,528.51,902.93,1574.08,1745,880,396.49,14,152.84,207,0.35,20]

In my last question I was asked this, so I already put it, pg_query returns a query resourse to BD and pg_fetch_row (I know you have the method that links the table column names, but then I would work with an obj and prefer to work with the array q is more direct, and yes, I have tested using pg_fetch_assoc and it n converts into an obj, continues as string as well and not from the error in JSON.parse in either) returns a resourse query row as an array.

Code snippet from the request:

$.post("query.php", {ano_ref: ano_base},
    function(retorno){
        var resposta = JSON.stringify(retorno);
        console.log("Data retorno: " + retorno + "Data resposta: " + resposta + "É uma string? " + typeof resposta);
        var vetor = JSON.parse(resposta);
        console.log("Data retorno: " + retorno + "Data vetor: " + vetor + "É um array? " + typeof vetor);
});

The results of the console:

inserir a descrição da imagem aqui

I know it’s a mess, but that’s what I’ve been able to do so far. There are n t and s dps that perform the stringfy that I have no idea where it came from. I imagine maybe that’s where the mistake came from. Another detail, I tried to convert the string that comes from the request in hand, putting in a string and doing the same process, and it works, which leads me to conclude that the format of the JSON that comes has no problems, I copied and pasted straight from the page (there is the msm php snippet in the main code, as I said to make it easy for me to see what was happening).

Suggestion of the comments*:

<?php

    include("conexao_postgres.php");

    $sql = "SELECT * FROM public.parametros_estaduais WHERE ano_base = 2016";
    $resultado = pg_query($dbconn, $sql);
    $resultado_array = pg_fetch_row($resultado);

    //echo json_encode($resultado_array, JSON_NUMERIC_CHECK | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE);
    $json = array();
    for($i=0; $i < count($resultado_array); $i++){
        $json[$i] = $resultado_array[$i];
    }
    echo(json_encode($json, JSON_NUMERIC_CHECK));
?>
  • Have you already validated your Json here? https://jsonformatter.curiousconcept.com/

  • I just validated it, all right. As I said, I made a string with it in my hand and used the stringfy and parse to test if the problem was in the json format, but he converted it right to the array. The problem apparently is not in [2016,0.02,347.58,528.51,902.93,1574.08,1745,880,396.49,14,152.84,207,0.35,20]

  • Post your Json instead of image @Állan!

  • I put in bold there in the description to be clearer, is exactly that @Marconi

  • Look, it works fine. https://jsfiddle.net/b0u750L1/

  • It was exactly this test that I did, if you create a string and do it, it works, but not in my code. Do you understand my dilemma? of a check in the console image. You’ll notice that I give a stringfy of the result to the answer, it converts Undefined to string (with several t n r that I don’t know where it came from) and then I parse it to vector, but it doesn’t convert pro array and also not from the error in the console. I even put an Alert(vector[0]) that should print "2016", but print blank.

  • Exchange the: JSON.stringify for: JSON.parse

  • The first code I made was like this. If I do not stringfy it da: Unexpected Character at line 1 column 2 of the JSON data from what I understand is pq return is typeof Undefined

  • Try generating json in php, instead of catching the result from select. Type: https://answall.com/questions/197484/retorno-com-array-em-json-mostrando-apenas-primeiro-registro/197493#197493

  • @Jessika edited and put at the end what I understood of what you suggested to me. I hope you understood correctly. If it is, the problem continues

  • Name the columns you are using in select q I will try to help you

  • I take them all, but I have a strong intuition that the mistake is in stringfy. "SELECT ano_base, ipva_monthly, preco_pneu_veiculo1, preco_pneu_veiculo2, preco_pneu_veiculo3, preco_pneu_veiculo4, salari_motorista, salario_companion, obligatory, enforced_syndical_pf, enforce_syndical_pj, dias_letivos_ano, addil_estrada_terra, dias_mes FROM public.parametros_state WHERE ano_base = $ano_base";

  • Try to take the escapes with replace, aq has an example: http://stackoverflow.com/questions/4253367/how-to-escape-a-json-string-containing-newline-characters-using-javascript after um json.parse in the string and ve is generated its object

  • I was able to solve it, deleted it and used Val, as magic worked. Now I just need to close the details, thanks a lot for the help @Jessika.

Show 9 more comments

1 answer

1

Problem solved as follows:

$.post("query.php", {ano_ref: ano_base},
    function(retorno){
        // Decodificando JSON para object/array
        var dados = eval('(' + retorno.toString() + ')');
        tratarDados(dados);
});

Browser other questions tagged

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