使用PHP json_encode()防止引用某些值

Bil*_*ami 5 php json

当使用PHP的json_encode将数组编码为JSON字符串时,是否有任何方法可以阻止函数在返回的字符串中引用特定值?我问的原因是因为我需要javascript来将对象中的某些值解释为实际的变量名,例如现有javascript函数的名称.

我的最终目标是使用输出的json作为ExtJS Menu组件的配置对象,因此引用所有内容的事实阻止我成功设置子项数组的"handler"(单击事件处理函数)等属性.

Bil*_*ami 0

这就是我最终所做的,这与我认为上面斯特凡建议的非常接近:

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

    /**
     * Encode object
     * 
     * 
     * @param     array   $properties
     * @return    string 
     */
    function encode($properties=array())
    {
        $output    = '';
        $enc_left  = $this->is_assoc($properties) ? '{' : '[';
        $enc_right = ($enc_left == '{') ? '}' : ']';

        foreach($properties as $prop => $value)
        {
            //map 'true' and 'false' string values to their boolean equivalent
            if($value === 'true')  { $value = true; }
            if($value === 'false') { $value = false; }

            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))  : '\''.$value.'\'';
                }
                else if(is_bool($value))
                {
                    $output .= ($value ? 'true' : 'false');
                }
                else
                {
                    $output .= $value;
                }

                $output .= ',';
            }
        }

        $output = rtrim($output, ',');
        return $enc_left.$output.$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;
    }
}
Run Code Online (Sandbox Code Playgroud)