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?

Answer from aleation on Stack Overflow
Top answer
1 of 5
14

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?

2 of 5
8

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.

Discussions

php - json_decode value without quotes - Stack Overflow
Being supplied a feed from external source but the value which is meant to be a number on a few entries is being filled with strings which is breaking looping over them [ { "id": 10... More on stackoverflow.com
🌐 stackoverflow.com
php - Remove double quote in json_encode() - Stack Overflow
You can use this bellow code to remove quote from numeric value. ... It will work >=PHP 5.3. $encoded = json_encode($data, JSON_NUMERIC_CHECK); More on stackoverflow.com
🌐 stackoverflow.com
Working around a single-quote with json_encode; best practices? | MODX Community Forums
The php script pulls the data from ... (via json_encode). Today I entered in a couple of new citations. One of them had a title with "Authors' Financial...". This broke it. I would get and 'Unexpected Identifier' error in console and viewing tinymce.citations.php showed the single-quote as the ... More on forums.modx.com
🌐 forums.modx.com
How do I json_encode without those quotes for the coordinates in leaflet geojson polygon? - Geographic Information Systems Stack Exchange
Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI ... More on gis.stackexchange.com
🌐 gis.stackexchange.com
February 6, 2015
🌐
PHP
php.net › manual › en › function.json-encode.php
PHP: json_encode - Manual
A note about json_encode automatically quoting numbers: It appears that the json_encode function pays attention to the data type of the value.
🌐
SSOJet
ssojet.com › dev guides › escaping › json escaping in php
JSON Escaping in PHP | Developer Guides
December 12, 2025 - When generating JSON strings in PHP, certain characters within your string values require escaping to maintain valid JSON structure. These include double quotes ("), backslashes (\), and control characters like newlines (\n) or tabs (\t). PHP’s json_encode() function handles this automatically, transforming these special characters into their escaped representations (e.g., \", \\, \n).
🌐
MODX Community
forums.modx.com › thread › 89889 › working-around-a-single-quote-with-json-encode-best-practices
Working around a single-quote with json_encode; best practices? | MODX Community Forums
&# 039; in the value (the space is in there to prevent it from becoming a '). I also perform the $modx->db->escape function on the data being json_encod(ed) as the double-quotes were also breaking it early on. $output = json_encode($modx->db->escape($data)); Everything works now, but this feels pretty hacky to me and wanted to know how others have solved this problem. ... It is a bit difficult to understand what you are doing without the code or a flow diagram.
Find elsewhere
Top answer
1 of 2
3

In the javascript code the array is treated as a string so try to parse this sting as json before using , then assign the result to coordinates . So if your result in success function is result , parse its coordinates attribute before using it this is example how to do so :

      result = {
     "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "properties": {
            "unitID": "001",
            "milesSq": "111.000000", "acres": "222.000000"
        },
        "geometry": [
            {
                "type": "Polygon",
                "coordinates": "[[[-109.048595341028587, 40.834756771179649], [-108.966734749488324, 40.562222787215255],  [-109.048595341028587, 40.834756771179649]]]"
            }
          ]
        }
       ]
     }


$.each(result.features, function (index, polygons) {
    $.each(polygons.geometry, function (index, geo) {
    console.log(geo.coordinates);
    var coordinates = JSON.parse(geo.coordinates);
    geo.coordinates = coordinates;


})
})


console.log(result)

  ///////  here u can start using the result object
  ///////   the leaflet code goes here 

OR in the php code you can decode the stringified array before passing it like this :

 $geometry['coordinates']=json_decode($geometry['coordinates']);

Hope this helps.

2 of 2
0

It works but abit tricky way...

$.each(layer.data.features, function(index, polygons) { var coordinates = JSON.parse(polygons.geometry.coordinates); var values = []; var coord = []; for(var i = 0, l = coordinates.length; i < l; i++) { values.push(coordinates[i]); }
coord.push(values); var campus = { 'type': 'Feature', 'properties': { 'name': polygons.properties.name, 'category': polygons.properties.category, 'description': polygons.properties.description, 'style': { weight: 2, color: polygons.properties.style.color, opacity: 1, fillColor: polygons.properties.style.color, fillOpacity: 0.4 }}, 'geometry': { 'type': 'Polygon', 'coordinates': coord } };

                            var poly  = L.geoJson(campus,  {
                                                        style: function (feature) {
                                                            return feature.properties && feature.properties.style;
                                                        },
                                                        onEachFeature: onEachPolygonFeature,

                            });
                            map.addLayer(poly); 

                        });
Top answer
1 of 7
3

What we do is (and that's what Zend_Json::encode() does too), is to use a special marker class that encapsulates Javascript expressions in a special class. The encoding then walks recursively through our array-to-be-encoded, replaces all marker instances with some string. After using the built-in json_encode() we simply do a string replace to replace each special string with the __toString() value of the respective marker instance.

You can either use Zend_Json directly (if that's possible) or check how they do it and adapt the code to your needs.

2 of 7
2

Bill's function almost worked, it just needed the is_assoc() function added.

But while I was sorting this out, I cleaned it up a bit. This seems to work quite well for me:

<?php

/**
 * JSObject class.
 */

class JSObject {
    var $jsexp = 'JSEXP:';

    /**
     * is_assoc function.
     *
     * Determines whether or not the object is an associative array
     * 
     * @access public
     * @param mixed $arr
     * @return boolean
     */
    function is_assoc($arr) {
        return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
    }

    /**
     * Encode object
     *
     * Encodes the object as a json string, parsing out items that were flagged as objects so that they are not wrapped in double quotes.
     *
     * @param     array   $properties
     * @return    string
     */
    function encode($properties = array()) {

        $is_assoc = $this->is_assoc($properties);

        $enc_left  = $is_assoc ? '{' : '[';
        $enc_right = $is_assoc ? '}' : ']';

        $outputArray = array();

        foreach ($properties as $prop => $value) {

            if ((is_array($value) && !empty($value)) || (is_string($value) && strlen(trim(str_replace($this->jsexp, '', $value))) > 0) || is_int($value) || is_float($value) || is_bool($value)) {

                $output = (is_string($prop)) ? $prop.': ' : '';

                if (is_array($value)) {
                    $output .= $this->encode($value);
                }
                else if (is_string($value)) {
                    $output .= (substr($value, 0, strlen($this->jsexp)) == $this->jsexp) ?  substr($value, strlen($this->jsexp))  : json_encode($value);
                }
                else {
                    $output .= json_encode($value);
                }


                $outputArray[] = $output;
            }
        }

        $fullOutput = implode(', ', $outputArray);

        return $enc_left . $fullOutput . $enc_right;
    }

    /**
     * JS expression
     *
     * Prefixes a string with the JS expression flag
     * Strings with this flag will not be quoted by encode() so they are evaluated as expressions
     *
     * @param   string  $str
     * @return  string
     */
    function js($str) {
        return $this->jsexp.$str;
    }
}
🌐
Stack Overflow
stackoverflow.com › questions › 63234846
php - Display JSON_Encoded string variable, in HTML, without quotes - Stack Overflow
The issue is that the displayed data has quotes. How can I ensure that quotes are not displayed when presenting the variable data on the webpage? ... It's not JSON without the quotes.
🌐
W3Schools
w3schools.com › php › func_json_encode.asp
PHP json_encode() Function
zip_close() zip_entry_close() zip_entry_compressedsize() zip_entry_compressionmethod() zip_entry_filesize() zip_entry_name() zip_entry_open() zip_entry_read() zip_open() zip_read() PHP Timezones ... The json_encode() function is used to encode a value to JSON format.
🌐
Stack Overflow
stackoverflow.com › questions › 26957871 › php-json-encode-without-quotes-in-first-and-end
android - php json_encode without quotes in first and end - Stack Overflow
November 16, 2014 - Part of PHP and Mobile Development Collectives · 1 · i have a json_encode with special character so i use these code to json encoding that character : function jsonRemoveUnicodeSequences($struct) { return preg_replace("/\\\\\\\u([a-f0-9]{4})/e", 'iconv(\'UCS-4LE\',\'UTF-8\',pack(\'V\', hexdec(\'U$1\')))', json_encode($struct)); } but with this code my json have quotation in first and end : "{\"category\":[{\"id\":\"4\",\"title\":\"سشیش\",\"image\":\"یبیسبیس\",\"created_at\":\"2014-11-15 22:58:19\"},{\"id\":\"5\",\"title\":\"بشیبش\",\"image\":\"بشبشبش\",\"created_at\":\"2014-11-15 23:07:19\"}],\"success\":1}" i want to delete just first and end quotation for android method can read this .
🌐
Kirby Forum
forum.getkirby.com › the cms › questions
Generating json, how do I escape double quotes? - Questions - Kirby Forum
February 20, 2022 - Hi, I’m generating some json for SEO in the header. But running into issues if there are quotes in the title. For example: "name": " ", If the title is: This is a “great” title The json would be: { "name": "This is a "great" title", } Thus, an invalid json. Any ideas?
🌐
Reddit
reddit.com › r/phphelp › json_encode adds backslashes to a php object even when json_unescaped_slashes is used
r/PHPhelp on Reddit: Json_encode adds backslashes to a PHP object even when JSON_UNESCAPED_SLASHES is used
November 30, 2021 -

check this example

    <?php
    $data = '"data": {
            "apiRequest": "{\"signature\":\"I3d4b8680011fa544e9d5dab9f3\"\"\"}", }';
    
    $message = new stdClass();
    
    $message->status = 'success';
    
    $message->data = stripslashes($data);
    
    var_dump($message);
    
    $json = json_encode($message, JSON_UNESCAPED_SLASHES);
    
    var_dump($json);

if you do

var_dump($message);

There are no slashes there, because they got removed by stripslashes

If you do

var_dump($json);

The slashes are added again, even though JSON_UNESCAPED_SLASHES is used.

Why is that and how to remove the slashes?

🌐
Pontikis
pontikis.net › blog › how-to-escape-json-special-characters-using-php
How to Escape JSON Special Characters using PHP - pontikis.net
July 6, 2024 - These characters are double quotes (“), backslash () and control characters (most inportant in common use is new line character). You don’t have to escape single quotes. For details, see here. ... The ideal way to escape a string with php, before create a json string is json_encode.