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 OverflowFirst, 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.
php - json_decode value without quotes - Stack Overflow
php - Remove double quote in json_encode() - Stack Overflow
Working around a single-quote with json_encode; best practices? | MODX Community Forums
How do I json_encode without those quotes for the coordinates in leaflet geojson polygon? - Geographic Information Systems Stack Exchange
You can use this bellow code to remove quote from numeric value.
http://php.net/manual/en/json.constants.php
It will work >=PHP 5.3.
$encoded = json_encode($data, JSON_NUMERIC_CHECK);
If you add an underscore to your regex at the end it will do it.
$array_final = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9_]*)":/','
array_final);
I assume that's what that preg_replace is for anyway.
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.
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);
});
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.
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;
}
}
You can either fix the JSON at the source so that it returns a valid JSON structure, or you can manually add quotes around the keys.
This answer to a similar question has an example of how to do that:
function my_json_decode($s) {
$s = str_replace(
array('"', "'"),
array('\"', '"'),
$s
);
$s = preg_replace('/(\w+):/i', '"\1":', $s);
return json_decode(sprintf('{%s}', $s));
}
If you can't turn that into valid JSON at the source, then you can use Services_JSON from PEAR to parse it, since adding quotes around the key is a non-trivial error-prone process.
Services_JSON will correctly parse the invalid key string.
Example:
$json = new Services_JSON();
var_dump($json->decode('{key:"value"}'));
Output:
object(stdClass)#2 (1) {
["key"]=>
string(5) "value"
}
You can try this solution:
$a = array( 'a' => 'apple' , 'b' => 'banana' );
$res = '';
foreach ($a as $key => $value){;
$res .= "{$key}:'{$value}',";
}
$res = rtrim($res, ',');
$res = sprintf("%s%s%s","{", $res, "}");
echo($res);
You can use preg_replace
$a = array( 'a' => 'apple' , 'b' => 'banana' , 'c' => 'orange' );
$a = json_encode($a);
$yourJSON = own_format($a);
print_r($yourJSON);
//{a:'apple',b:'banana'}
function own_format($jsonData){
$pattern = array('/{"/i','/":/i','/,"/i');
$preg = preg_replace($pattern[0], "{", $jsonData);
$preg = preg_replace($pattern[1], ":", $preg);
$preg = preg_replace($pattern[2], ",", $preg);
$Output = str_replace('"',"'",$preg);
return $Output;
}
When I test this portion of code :
echo json_encode(array( 'foo' => 'bar'));
die;
I get :
{"foo":"bar"}
Which is valid JSON.
(Note these are double-quotes, and not simple-quotes as you posted)
The ouput you are asking for :
{ foo : 'bar' }
is valid Javascript, but is not valid JSON -- so json_encode will not return that.
See json.org for the specification of the JSON format -- which is a subset of Javascript, and not Javascript itself.
Instead of "stripping the quotes out myself with some ugly regex", you should adapt your code, so it accepts valid JSON : this is way better, in my opinion.
If you want to convert your JSON to print a javascript object (that was my case) you can use ugly regex like this:
$myJsonString = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $myJsonString);
Source: https://hdtuto.com/article/php-how-to-remove-double-quotes-from-json-array-keys
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?