When using PHP\'s json_encode to encode an array as a JSON string, is there any way at all to prevent the function from quoting specific values in the returned string? The r
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:
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;
}
}