Json poorly formed by PHP function

0

I'm putting together a json in a php function and taking it in js gives me an error when wanting to parse it.

When I validated it on a page, it says it's invalid, by deleting it:

  

messan "[]"

I can validate it correctly.

Some idea of how to create the json without

  

messan "[]"

That's my php function and the response it generates.

PHP
    $resultado = "[";
                foreach($valores as $k=>$v){
                    $v["X"] = rounded($v["X"]);
                    $v["Y"] = rounded($v["Y"]);
                    $v["A"] = rounded($v["A"]);
                    $v["L"] = rounded($v["L"]);
                    $v["T"] = rounded($v["T"]);
                    $resultado .= "{dia:'".$k."',";
                    $resultado .= "X:'".number_format($v['X'])."',";
                    $resultado .= "Y:'".number_format($v['Y'])."',";
                    $resultado .= "A:'".number_format($v['A'])."',";
                    $resultado .= "L:'".number_format($v['L'])."',";
                    $resultado .= "T:'".number_format($v['T'])."'},";   
                } 
                $resultado = trim($resultado, ",");
                $resultado .= "]";  

                $retorno1 = $resultado;

Respuesta
    mesano"[{dia:'01-08-2016',X:'0',Y:'5',A:'38',L:'31',T:'35'}]"
    
asked by Stevn 22.08.2017 в 15:15
source

1 answer

0
  

The problem is that your JSON is malformed, all strings including keys / keys must be wrapped in double quotes.

Solution 1

$resultado = "[";
foreach($valores as $k=>$v){
    $resultado .= '{ "dia": "'.$k.'",';
    $resultado .= ' "Xv": "'.number_format(rounded($v["X"])).'",';
    $resultado .= ' "Y": "'.number_format(rounded($v["Y"])).'",';
    $resultado .= ' "A": "'.number_format(rounded($v["A"])).'",';
    $resultado .= ' "L": "'.number_format(rounded($v["L"])).'",';
    $resultado .= ' "T": "'.number_format(rounded($v["T"])).'"},'; 
}
$resultado = trim($resultado, ",");
$resultado .= "]";  

$retorno1 = $resultado;

Solution 2

$valores = ...;
$resultados = [];

foreach($valores as $key => $value) {
  $resultado = [
    "dia" => $key,
    "Xv" => number_format(rounded($value["X"])),
    "Y" => number_format(rounded($value["Y"])),
    "A" => number_format(rounded($value["A"])),
    "L" => number_format(rounded($value["L"])),
    "T" => number_format(rounded($value["T"]))
  ];
  array_push($resultados, (object) $resultado);
}

$json = json_encode($resultados, true);
    
answered by 22.08.2017 в 15:26