如何json_encode php数组,但没有引号的键

时间:2022-12-21 21:34:34

I'm trying to plot (with Flot) a pie chart with some data

我正在尝试绘制(使用Flot)带有一些数据的饼图

var data = <?php echo json_encode($data)?>

The result I get from that is this:

我得到的结果是这样的:

var data = [
{"label":"Crear Usuario", "data":"2"},
{"label":"Impresoras", "data":"1"},
{"label":"Problema Correo", "data":"1"},
{"label":"Requisicion Equipo", "data":"1"},
{"label":"Sitio Web", "data":"1"}
]

The problem here is that I need the label and data without the quotes, I already tried json_encode($data, JSON_NUMERIC_CHECK); but only removes the quotes from the numbers.

这里的问题是我需要没有引号的标签和数据,我已经尝试过json_encode($ data,JSON_NUMERIC_CHECK);但只删除数字中的引号。

The following format is what I need:

我需要以下格式:

var data = [
    {label:"Crear Usuario",data:2}, ...

3 个解决方案

#1


11  

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

首先,你必须在php中生成你的数组,所以数据的值是整数,而不是字符串:

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

我从你的json_encode()模拟你的数组,我想它看起来像这样(或它应该):

$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.
  • 请注意,2和1是不带引号的,因此它们是整数,这很重要。

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

然后你在Javascript中错过了JSON.parse()来实际将输出变成json对象:

<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
  • 请注意,var data = ...是SINGLE QUOTED,因此您将php中的echo作为String捕获

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

console.log()为我输出这个:

[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?

看起来你需要什么,对吗?

#2


5  

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.

引用和不带引号的键之间没有区别。问题在于引用实际数据值,因为Flot需要数字而不是字符串。

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.

json_encode函数根据您提供的数据类型决定是否引用。在这种情况下,它看起来像你正在执行的任何操作来创建$ data正在生成字符串值而不是整数。您需要重新检查这些操作,或者明确告诉PHP将它们解释为数字,使用(int)或(float)转换或intval / floatval函数。

#3


3  

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}"

#1


11  

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

首先,你必须在php中生成你的数组,所以数据的值是整数,而不是字符串:

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

我从你的json_encode()模拟你的数组,我想它看起来像这样(或它应该):

$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.
  • 请注意,2和1是不带引号的,因此它们是整数,这很重要。

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

然后你在Javascript中错过了JSON.parse()来实际将输出变成json对象:

<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
  • 请注意,var data = ...是SINGLE QUOTED,因此您将php中的echo作为String捕获

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

console.log()为我输出这个:

[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?

看起来你需要什么,对吗?

#2


5  

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.

引用和不带引号的键之间没有区别。问题在于引用实际数据值,因为Flot需要数字而不是字符串。

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.

json_encode函数根据您提供的数据类型决定是否引用。在这种情况下,它看起来像你正在执行的任何操作来创建$ data正在生成字符串值而不是整数。您需要重新检查这些操作,或者明确告诉PHP将它们解释为数字,使用(int)或(float)转换或intval / floatval函数。

#3


3  

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}"