【问题标题】:Parsing Javascript (not JSON) in PHP在 PHP 中解析 Javascript(不是 JSON)
【发布时间】:2009-10-12 11:46:07
【问题描述】:

我有一个包含 javascript 对象序列化的 php 字符串:

$string = '{fu:"bar",baz:["bat"]}';

当然,实际的字符串要复杂得多,但仍然是格式良好的 javascript。这不是标准 JSON,因此 json_decode 失败。你知道任何可以解析这个字符串并返回一个 php 关联数组的 php 库吗?

【问题讨论】:

  • 请解释为什么你不能 JSONify 它。这将大大简化一切。
  • 如前所述,这是不是有效的 JSON。有效的 JSON 要求对象键的格式类似于字符串,即用双引号括起来。
  • 我正在回复一条现已删除的评论。我无法制作有效的字符串,因为我没有制作字符​​串。其他人会这样做。
  • 它不是标准的 JSON,而是标准的 Javascript。因此我的问题的标题。
  • 8 cmets 以达到已经显而易见的目标。干得好:D

标签: php javascript


【解决方案1】:

这听起来像是一个有趣的挑战,所以我编写了一个小型解析器:D

class JsParserException extends Exception {}
function parse_jsobj($str, &$data) {
    $str = trim($str);
    if(strlen($str) < 1) return;

    if($str{0} != '{') {
        throw new JsParserException('The given string is not a JS object');
    }
    $str = substr($str, 1);

    /* While we have data, and it's not the end of this dict (the comma is needed for nested dicts) */
    while(strlen($str) && $str{0} != '}' && $str{0} != ',') { 
        /* find the key */
        if($str{0} == "'" || $str{0} == '"') {
            /* quoted key */
            list($str, $key) = parse_jsdata($str, ':');
        } else {
            $match = null;
            /* unquoted key */
            if(!preg_match('/^\s*[a-zA-z_][a-zA-Z_\d]*\s*:/', $str, $match)) {
            throw new JsParserException('Invalid key ("'.$str.'")');
            }   
            $key = $match[0];
            $str = substr($str, strlen($key));
            $key = trim(substr($key, 0, -1)); /* discard the ':' */
        }

        list($str, $data[$key]) = parse_jsdata($str, '}');
    }
    "Finshed dict. Str: '$str'\n";
    return substr($str, 1);
}

function comma_or_term_pos($str, $term) {
    $cpos = strpos($str, ',');
    $tpos = strpos($str, $term);
    if($cpos === false && $tpos === false) {
        throw new JsParserException('unterminated dict or array');
    } else if($cpos === false) {
        return $tpos;
    } else if($tpos === false) {
        return $cpos;
    }
    return min($tpos, $cpos);
}

function parse_jsdata($str, $term="}") {
    $str = trim($str);


    if(is_numeric($str{0}."0")) {
        /* a number (int or float) */
        $newpos = comma_or_term_pos($str, $term);
        $num = trim(substr($str, 0, $newpos));
        $str = substr($str, $newpos+1); /* discard num and comma */
        if(!is_numeric($num)) {
            throw new JsParserException('OOPSIE while parsing number: "'.$num.'"');
        }
        return array(trim($str), $num+0);
    } else if($str{0} == '"' || $str{0} == "'") {
        /* string */
        $q = $str{0};
        $offset = 1;
        do {
            $pos = strpos($str, $q, $offset);
            $offset = $pos;
        } while($str{$pos-1} == '\\'); /* find un-escaped quote */
        $data = substr($str, 1, $pos-1);
        $str = substr($str, $pos);
        $pos = comma_or_term_pos($str, $term);
        $str = substr($str, $pos+1);        
        return array(trim($str), $data);
    } else if($str{0} == '{') {
        /* dict */
        $data = array();
        $str = parse_jsobj($str, $data);
        return array($str, $data);
    } else if($str{0} == '[') {
        /* array */
        $arr = array();
        $str = substr($str, 1);
        while(strlen($str) && $str{0} != $term && $str{0} != ',') {
            $val = null;
            list($str, $val) = parse_jsdata($str, ']');
            $arr[] = $val;
            $str = trim($str);
        }
        $str = trim(substr($str, 1));
        return array($str, $arr);
    } else if(stripos($str, 'true') === 0) {
        /* true */
        $pos = comma_or_term_pos($str, $term);
        $str = substr($str, $pos+1); /* discard terminator */
        return array(trim($str), true);
    } else if(stripos($str, 'false') === 0) {
        /* false */
        $pos = comma_or_term_pos($str, $term);
        $str = substr($str, $pos+1); /* discard terminator */
        return array(trim($str), false);
    } else if(stripos($str, 'null') === 0) {
        /* null */
        $pos = comma_or_term_pos($str, $term);
        $str = substr($str, $pos+1); /* discard terminator */
        return array(trim($str), null);
    } else if(strpos($str, 'undefined') === 0) {
        /* null */
        $pos = comma_or_term_pos($str, $term);
        $str = substr($str, $pos+1); /* discard terminator */
        return array(trim($str), null);
    } else {
        throw new JsParserException('Cannot figure out how to parse "'.$str.'" (term is '.$term.')');
    }
}

用法:

$data = '{fu:"bar",baz:["bat"]}';    
$parsed = array();    
parse_jsobj($data, $parsed);    
var_export($parsed);

给予:

array (
  'fu' => 'bar',
  'baz' =>
  array (
    0 => 'bat',
  ),
)

用这些字符串测试:

'{fu:"bar",baz:["bat"]}',
'{rec:{rec:{rec:false}}}',
'{foo:[1,2,[3,4]]}',
'{fu:{fu:"bar"},bar:{fu:"bar"}}',
'{"quoted key":[1,2,3]}',
'{und:undefined,"baz":[1,2,"3"]}',
'{arr:["a","b"],"baz":"foo","gar":{"faz":false,t:"2"},f:false}',

【讨论】:

  • 真的很不错。两个注意事项: Javascript 对象键可以用单引号或双引号括起来(通常如果键不是有效标识符(例如包含空格))。并且 undefined 是一个有效值。
  • 我想如果一个对象包含在另一个对象的值中并且 strrpos 不正确,例如 '{fu:{fu:"bar"},bar:{fu :"bar"}}'
  • 我认为现在可以了,我已经修复了 dicts 中的 dicts 和数组中的数组的一些错误。您的测试字符串现在可以工作了。
  • 这个版本处理带引号的键,并将 undefined 转换为 null。
  • @gnud 您的代码在以下 javascript 对象 {name:"Andrew", age: "11", Toys: { car​​: [{color:"red", wheel: "1"} 上中断, {颜色:“白色”,车轮:“4”}]},公共汽车:[ {av:“Mug 2013”​​,var:[ {颜色:“红色”,车轮:“10”},{颜色:“白色” , 轮子: "34"}], totl: 10,buy: true}]}
【解决方案2】:

感谢 luttkens

Yii 框架的CJON::decode() 类完美运行!

require_once ($_SERVER['DOCUMENT_ROOT']."/phplib/CJSON.php");

$json = new CJSON();
$data = $json->decode('{ url : "/jslib/maps/marker/marker_red.png", height : 34, width : 20, anchorIcon : [5,25.5], anchorText : [0,2], }', true);

print_r( $data );

结果:

Array
(
    [url] => /jslib/maps/marker/marker_red.png
    [height] => 34
    [width] => 20
    [anchorIcon] => Array
        (
            [0] => 5
            [1] => 25.5
        )

    [anchorText] => Array
        (
            [0] => 0
            [1] => 2
        )

)

【讨论】:

    【解决方案3】:

    Pear Services_JSON 将解析该字符串(测试版本 1.31)。但鉴于这是一个 JSON 解析器并且这不是有效的 JSON,您无法保证未来的版本仍然可以工作。

    【讨论】:

      【解决方案4】:

      我发现 Yii 框架的 CJSON::decode() 函数也可以处理 Javascript 对象。

      如果你不使用 Yii,你应该可以使用 source code

      【讨论】:

      • 对于 encoding JavaScript 对象(和标量值),请查看 CJavaScript,它在编码方面做得很好。
      【解决方案5】:

      那个图书馆呢? http://timwhitlock.info/tag/jparser/

      我还没试过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-05
        • 1970-01-01
        • 2012-09-17
        • 2018-04-29
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        • 2012-01-21
        相关资源
        最近更新 更多