json text split reg expression or parser

心不动则不痛 提交于 2019-12-12 01:13:48

问题


$var ="
   { 
        key : { 
            key_deep :  val\{ue   /* should be "val{ue" as { is escaped  */
        } , 
        key2 : value
    }

";
print_r(preg_split('//',$var));
// array( 
//    array( 
//       'key'=> array(
//           'key_deep'=> 'val{ue'
//        )
//    ), 
//    array('key2'=>'value')
// );

is there a regular expression to split this using preg_split in php?

basically I need the same as json_decode() but without the need of the the quotes on BOTH value and key and the only thing escaped are four characters \{ \, \} \:


回答1:


You're probably going to want to look at a parser rather than a regular expression, given the arbitrary nesting that could occur here.

Try:

http://pear.php.net/package/PHP_ParserGenerator/redirected

or

http://www.hwaci.com/sw/lemon/

or

http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=php+parser+generator




回答2:


Well for one thing that json is incorrect and will spew out an error on json_decode.

read the specs for json here

One correct implementation of the json is:

$var ='
   { 
        "key" : { 
            key_deep :  "val\{ue" 
        } , 
        "key2" : "value"
   }
';

Also json_decode never yields an Array it yields a object(stdClass) unless you add the true parameter



来源:https://stackoverflow.com/questions/6099891/json-text-split-reg-expression-or-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!