2013-11-03 69 views
0

這是我原來的JSON文件「幽靈」斜線,將項目添加到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)); 
?> 

這是生成的文件d ata.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"} 
] 

我做什麼,除去反斜槓?感謝您的幫助

+2

這只是PHP矯枉過正。不用擔心,JSON仍然有效,並且字符串具有**完全**的值,而且沒有不必要的反斜槓。 –

+0

或'JSON_UNESCAPED_SLASHES'如其他幾十個副本中的一個所述。 – mario

+0

@ Francisco:如果下面的答案之一解決了您的問題,Stack Overflow的工作方式,您可以通過單擊左側的複選標記來「接受」答案。更多:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

回答

1

您不需要刪除那些反斜槓,它們只是逃避角色。

讀取該JSON格式的字符串後,那些\/的序列將自動轉換爲/

+0

爲什麼downvote? –

+0

非常感謝。我有兩天有這個問題「沒問題」 –

1

你有什麼是完全有效的JSON,但如果你想刪除它,你可以用JSON_UNESCAPED_SLASHES不斷做:

file_put_contents('data.json', json_encode($data, JSON_UNESCAPED_SLASHES)); 
+0

非常感謝。我有兩天有這個問題「沒問題」 –

+0

@FranciscoJoséSeguraNoya:您的問題現在已解決? –

3

可以防止與JSON_UNESCAPED_SLASHES選項json_encode,看the documentation

但請注意,這只是PHP過度使用。 JSON仍然有效,並且字符串具有正好的字符相同的序列,它們將具有不必要的轉義字符。

+1

這個答案爲什麼downvoted?請解釋。 –

+0

非常感謝。我有兩天有這個問題「沒問題」 –