0

我有以下字符串。

$json = '
    insert: [
        { table:" abc",values:{id:1,text:" lorem ipsum "} },
        {   table  :  "cde "  ,  values   :   { id  : 2  , firstname  :  "lorem ipsum   dolor sit    " } } 
    ]
    ';

已经尝试使用下面的正则表达式,但结果出乎意料。

$json = preg_replace('~\s{1,}~', '', $json);

我喜欢下面的回报

 {"insert": [{"table": "abc", "values": {"id": 1, "text": "lorem ipsum"}}, {"table": "cde", "values": {"id": 2, "text": "lorem ipsum dolor sit"}}]}

然后使用json_decode()

我希望我已经清楚了

更新:

我有以下字符串。

例子:

$json_string = '
    insert: [
        { table:" abc",values:{id:1,text:" lorem ipsum "} },
        {   "  table  "  :  "cde "  ,  "  values"   :   { id  : 2  , firstname  :  "lorem ipsum   dolor sit    " } } 
    ]
    ';

我想要以下输出

$json_replaced = '{"insert": [{"table": "abc", "values": {"id": 1, "text": "lorem ipsum"}}, {"table": "cde", "values": {"id": 2, "text": "lorem ipsum dolor sit"}}]}';
4

2 回答 2

1

你不能只运行以下命令:

$json_string = preg_replace("/\s{2,}/", "", $json_string);

输出是:

insert: [{ table:" abc",values:{id:1,text:" lorem ipsum "} },{"table":"cde ","values":{ id: 2, firstname:"lorem ipsumdolor sit" } }]
于 2014-05-25T21:18:04.910 回答
0

以下应该为您工作:

$json = '
    insert: [
        { table:" abc",values:{id:1,text:" lorem ipsum "} },
        {   table  :  "cde "  ,  values   :   { id  : 2  , firstname  :  "lorem ipsum   dolor sit    " } } 
    ]
';
$json = '{' . $json . '}';
$json = preg_replace(array('/ *\n */', '/(?<=[{,]) *([^\s:]+) *: */'),
                     array("", '"$1": '), $json);
echo $json; // converted json string
print_r(json_decode($json, true)); // decoded array

现场演示:http: //ideone.com/wfxDYK

输出:

{"insert": [{"table": " abc","values": {"id": 1,"text": " lorem ipsum "} },{"table": "cde "  ,"values": {"id": 2  ,"firstname": "lorem ipsum   dolor sit    " } }]}

Array
(
    [insert] => Array
        (
            [0] => Array
                (
                    [table] =>  abc
                    [values] => Array
                        (
                            [id] => 1
                            [text] =>  lorem ipsum 
                        )

                )

            [1] => Array
                (
                    [table] => cde 
                    [values] => Array
                        (
                            [id] => 2
                            [firstname] => lorem ipsum   dolor sit    
                        )

                )

        )

)
于 2013-10-02T21:34:29.487 回答