0

这是我原来的 json 文件

data.json(之前)

[
{ "thumb": "../userfiles/img/min/m_1.jpg", "image": "../userfiles/img/1.jpg", "title": "Image 1", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_2.jpg", "image": "../userfiles/img/2.jpg", "title": "Image 2", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_3.jpg", "image": "../userfiles/img/3.jpg", "title": "Image 3", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_4.jpg", "image": "../userfiles/img/4.jpg", "title": "Image 4", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_5.jpg", "image": "../userfiles/img/5.jpg", "title": "Image 5", "folder": "Folder 1" }
]

这是我的 php 文件,它向文件 data.jon 添加了一个元素

add_json.php

<?
$dir_thumb  = '../userfiles/img/thumb/6_m.jpg';
$dir_img    = '../userfiles/img/6.jpg'; 
$title      = 'img_6';     
$tipo_image = 'news';

$json        = file_get_contents('data.json');
$data        = json_decode($json);

$data[]     = array(
             'thumb'=>  $dir_thumb,
             'image'=>  $dir_img,
             'title'=>  $title,
             'folder'=> $tipo_image         
        );
file_put_contents('data.json', json_encode($data));
?>

这是生成的文件 data.json

data.json(执行文件 add_json.php 后)

[   
{"thumb":"..\/userfiles\/img\/min\/m_1.jpg","image":"..\/userfiles\/img\/1.jpg","title":"Image 1","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_2.jpg","image":"..\/userfiles\/img\/2.jpg","title":"Image 2","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_3.jpg","image":"..\/userfiles\/img\/3.jpg","title":"Image 3","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_4.jpg","image":"..\/userfiles\/img\/4.jpg","title":"Image 4","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_5.jpg","image":"..\/userfiles\/img\/5.jpg","title":"Image 5","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/thumb\/6_m.jpg","image":"..\/userfiles\/img\/6.jpg","title":"img_6","folder":"news"}  
]

我该怎么做才能删除反斜杠?谢谢你的帮助

4

3 回答 3

3

您可以通过JSON_UNESCAPED_SLASHES选项来防止这种情况发生json_encode,请参阅文档

但请注意,这只是 PHP 的矫枉过正。JSON 仍然有效,并且字符串中的字符序列与没有不必要的转义字符时的字符序列完全相同。

于 2013-11-03T17:01:09.853 回答
1

您不需要删除那些反斜杠,它们只是转义字符。

在读取该 JSON 格式的字符串后,这些序列\/将自动转换为/.

于 2013-11-03T16:59:28.483 回答
1

你所拥有的是完全有效的 JSON,但如果你想删除它,你可以用JSON_UNESCAPED_SLASHES常量来做:

file_put_contents('data.json', json_encode($data, JSON_UNESCAPED_SLASHES));
于 2013-11-03T17:00:34.817 回答