How to json_encode php array but the keys without quotes

First, you have to generate your array in php so the data's value are integers, not strings:

I emulated your array from your json_encode(), I guess it looks like this (or it should):

$array =  array(
                array("label" => "Crear Usuario",   "data" => 2),
                array("label" => "Impresoras",      "data" => 1),
                array("label" => "Problema Correo", "data" => 1),
                array("label" => "Requisicion Equipo", "data" => 1),
                array("label" => "Sitio Web", "data" => 1)
            );

    $data = json_encode($array);
  • Notice that the 2 and 1's are unquoted, so this way they are integers, this is important.

Then you are missin in Javascript the JSON.parse() to actually make that output into a json object:

<script>
    var data = '<?php echo $data; ?>';
    var json = JSON.parse(data);
    console.log(json);
    console.log(json[0]);
</script>
  • Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String

The console.log()'s output this for me:

[Object, Object, Object, Object, Object] // First console.log(): one object with the 5 Objects. 
Object {label: "Crear Usuario", data: 2} // secons console log (json[0]) with the first object 

Looks like what you need, am I right?


There's no difference between quoted and unquoted keys. The problem is with the quoting around the actual data values, since Flot requires numbers, not strings.

The json_encode function decides to whether to quote based on the type of data you're giving it. In this case it looks like whatever operations you're performing to create $data are producing string values instead of integers. You need to re-examine those operations, or explicitly tell PHP to interpret them as numbers, using (int) or (float) casting, or the intval/floatval functions.


Try something like this:

function buildBrokenJson( array $data ) {

   $result = '{';

   $separator = '';
   foreach( $data as $key=>$val ) {
      $result .= $separator . $key . ':';

      if( is_int( $val ) ) {
         $result .= $val;
      } elseif( is_string( $val ) ) {
         $result .= '"' . str_replace( '"', '\"', $val) . '"';
      } elseif( is_bool( $val ) ) {
         $result .= $val ? 'true' : 'false';
      } else {
         $result .= $val;
      }

      $separator = ', ';
   }

   $result .= '}';

   return $result;
}

and when run

$a = array("string"=>'Crear "Usuario', 'foo'=>':', "int"=>2, "bool"=>false);
var_dump( buildBrokenJson($a) );

it gives:

string(54) "{string:"Crear \"Usuario", foo:":", int:2, bool:false}"