Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

javascript - How to json_encode php array but the keys without quotes

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

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.

The following format is what I need:

var data = [
    {label:"Crear Usuario",data:2}, ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...