我如何解码这个json?

时间:2017-04-26 14:22:05

标签: php json

嗨,我有解码json的问题,看起来像这样 代码:

$tmp=($this->request->post['info']);
    echo $tmp;

结果:

{"views":{},"vectors":"{\"front\":{},\"back\":{}}","teams":"{}","fonts":"","product_id":"217","parent_id":"0","design_id":null,"design_file":"blabla","designer_id":123,"design_key":0,"product_color":"Sapphire","user_id":"0","design_name":"asd","weight":0,"is_private":0}

如果我解码此结果为空

im tryung这样做但没有结果

    $tmp=json_encode($this->request->post['info']);
    echo $tmp;
    $tmp=str_replace('\'{','{',$tmp);//' dont even ask
    $tmp=str_replace('}\'','}',$tmp);
    $tmp=str_replace('"{','{',$tmp);//' dont even ask
    $tmp=str_replace('}"','}',$tmp);
    $tmp=stripslashes($tmp);
    echo $tmp;
    $tmp=json_decode($tmp,true);

    $data = $tmp;

结果保持不变...我只想解码:{"views":{},"vectors":"{\"front\":{},\"back\":{}}","teams":"{}","fonts":"","product_id":"217","parent_id":"0","design_id":null,"design_file":"blabla","designer_id":123,"design_key":0,"product_color":"Sapphire","user_id":"0","design_name":"asd","weight":0,"is_private":0}

无需将vectors解码为数组,我的意思是如果它保持字符串就可以了 也许"teams"附近的休息是理由?

2 个答案:

答案 0 :(得分:0)

所以:

<?php
$json = '{"views":{},"vectors":"{\"front\":{},\"back\":{}}","teams":"{}","fonts":"","product_id":"217","parent_id":"0","design_id":null,"design_file":"blabla","designer_id":123,"design_key":0,"product_color":"Sapphire","user_id":"0","design_name":"asd","weight":0,"is_private":0}';
$decoded = json_decode($json, true);
print_r($decoded);

屈服于我:

Array
(
    [views] => Array
        (
        )

    [vectors] => {"front":{},"back":{}}
    [teams] => {}
    [fonts] => 
    [product_id] => 217
    [parent_id] => 0
    [design_id] => 
    [design_file] => blabla
    [designer_id] => 123
    [design_key] => 0
    [product_color] => Sapphire
    [user_id] => 0
    [design_name] => asd
    [weight] => 0
    [is_private] => 0
)

哪个看起来完全有效。我认为你的行:

$tmp=json_encode($this->request->post['info']);

没有意义,因为它看起来像你有json格式的字符串,你再次编码。

你从前端获得的是字符串,你必须解码它才能获得数组(在我的情况下)或类。

答案 1 :(得分:-1)

$jsonEncodedString = json_encode($tmp); echo $jsonEncodedString;

你不必剥去任何斜线。反之。您必须将回声文本表示为PHP源代码。

反斜杠()是PHP和JSON中的特殊字符。两种语言都使用它来转义字符串中的特殊字符,为了在字符串中正确表示反斜杠,您必须在PHP和JSON中添加另一个反斜杠。

有两个特殊字符需要在单引号字符串中转义:撇号(&#39;)和反斜杠()。虽然撇号总是需要转义,但PHP解释器是宽容的,只要它们不会产生混淆,就允许使用未转义的反斜杠。但是,单引号字符串中反斜杠的正确表示是\。

http://php.net/manual/fr/function.json-decode.php