2010-10-13 50 views
5

我試圖將我的JSON對象寫入服務器上的.json文件。我現在做這個的方法是:將JSON對象寫入服務器上的.json文件

的JavaScript:

function createJsonFile() { 

    var jsonObject = { 
     "metros" : [], 
     "routes" : [] 
    }; 

    // write cities to JSON Object 
    for (var index = 0; index < graph.getVerticies().length; index++) { 
     jsonObject.metros[index] = JSON.stringify(graph.getVertex(index).getData()); 
    } 

    // write routes to JSON Object 
    for (var index = 0; index < graph.getEdges().length; index++) { 
     jsonObject.routes[index] = JSON.stringify(graph.getEdge(index)); 
    } 

    // some jQuery to write to file 
    $.ajax({ 
     type : "POST", 
     url : "json.php", 
     dataType : 'json', 
     data : { 
      json : jsonObject 
     } 
    }); 
}; 

PHP:

<?php 
    $json = $_POST['json']; 
    $info = json_encode($json); 

    $file = fopen('new_map_data.json','w+'); 
    fwrite($file, $info); 
    fclose($file); 
?> 

它寫精細的信息似乎是正確的,但它不能正常呈現。它是走出來的:

{"metros":["{\\\"code\\\":\\\"SCL\\\",\\\"name\\\":\\\"Santiago\\\",\\\"country\\\":\\\"CL\\\",\\\"continent\\\":\\\"South America\\\",\\\"timezone\\\":-4,\\\"coordinates\\\":{\\\"S\\\":33,\\\"W\\\":71},\\\"population\\\":6000000,\\\"region\\\":1}", 

...但我期待這樣的:

"metros" : [ 
    { 
     "code" : "SCL" , 
     "name" : "Santiago" , 
     "country" : "CL" , 
     "continent" : "South America" , 
     "timezone" : -4 , 
     "coordinates" : {"S" : 33, "W" : 71} , 
     "population" : 6000000 , 
     "region" : 1 
    } , 

任何想法,爲什麼我得到所有這些斜線的,爲什麼它是所有在同一行?

感謝, 斯托伊奇

+0

您使用的框架或前手在POST進行任何消毒,儘量在PHP ini和重啓轉彎magic_qoutes。 – RobertPitt 2010-10-13 12:23:04

回答

16

你是雙重編碼。沒有必要在JS PHP中進行編碼,只需在一邊做,然後只做一次。

// step 1: build data structure 
var data = { 
    metros: graph.getVerticies(), 
    routes: graph.getEdges() 
} 

// step 2: convert data structure to JSON 
$.ajax({ 
    type : "POST", 
    url : "json.php", 
    data : { 
     json : JSON.stringify(data) 
    } 
}); 

注意,dataType參數表示的預期響應類型,而不是你發送的數據類型。發佈請求默認爲application/x-www-form-urlencoded

我不認爲你需要這個參數。你可以修剪下來到:

$.post("json.php", {json : JSON.stringify(data)}); 

然後(在PHP)做到:

<?php 
    $json = $_POST['json']; 

    /* sanity check */ 
    if (json_decode($json) != null) 
    { 
    $file = fopen('new_map_data.json','w+'); 
    fwrite($file, $json); 
    fclose($file); 
    } 
    else 
    { 
    // user has posted invalid JSON, handle the error 
    } 
?> 
+0

應該不是fwrite($ file,$ json); ?? – Francesco 2011-05-14 04:33:35

5

不要JSON.stringify。通過這樣做你會得到一個雙JSON編碼。

您首先將數組元素轉換爲JSON字符串,然後將它們添加到完整對象中,然後編碼您的大對象,但是當對已編碼的元素進行編碼時,將被視爲簡單字符串,因此所有特殊字符被逃脫。你需要有一個大對象,並且只需編碼一次。編碼器會照顧孩子。

對於行問題嘗試發送JSON數據類型標頭:Content-type: text/json我認爲(沒有谷歌它)。但渲染將僅取決於您的瀏覽器。也可以使用縮進進行編碼。

+0

我想這工作...我想我需要做'JSON.stringify',以便它正確格式化我的對象?我爲我的對象定義了一個'toJSON'函數,這就是爲什麼我使用'stringify'的原因。我拿出來,它擺脫了\\\,但它仍然是在一條線上...... – Hristo 2010-10-13 07:25:46

+0

@Hristo:它是在一條線上的所有錯?我認爲你不應該在意。 – Tomalak 2010-10-13 07:33:00

+0

他可能需要檢查,如果在開發過程中,這可能會幫助他。如果只是爲了存儲,沒有什麼不對。 – 2010-10-13 07:36:51

0
<html> 
<head> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script> 
</head> 
<body> 
    <?php 
     $str = file_get_contents('data.json');//get contents of your json file and store it in a string 
     $arr = json_decode($str, true);//decode it 
     $arrne['name'] = "sadaadad"; 
     $arrne['password'] = "sadaadad"; 
     $arrne['nickname'] = "sadaadad"; 
     array_push($arr['employees'], $arrne);//push contents to ur decoded array i.e $arr 
     $str = json_encode($arr); 
     //now send evrything to ur data.json file using folowing code 
     if (json_decode($str) != null) 
      { 
      $file = fopen('data.json','w'); 
      fwrite($file, $str); 
      fclose($file); 
      } 
      else 
      { 
      // invalid JSON, handle the error 
      } 

     ?> 
    <form method=> 
</body> 

data.json

{ 
    "employees":[ 
    { 
    "email":"11BD1A05G9", 
    "password":"INTRODUCTION TO ANALYTICS", 
    "nickname":4 
    }, 
    { 
    "email":"Betty", 
    "password":"Layers", 
    "nickname":4 
    }, 
    { 
    "email":"Carl", 
    "password":"Louis", 
    "nickname":4 
    }, 
    { 
    "name":"sadaadad", 
    "password":"sadaadad", 
    "nickname":"sadaadad" 
    }, 
    { 
    "name":"sadaadad", 
    "password":"sadaadad", 
    "nickname":"sadaadad" 
    }, 
    { 
    "name":"sadaadad", 
    "password":"sadaadad", 
    "nickname":"sadaadad" 
    } 
    ] 
    } 
+0

evrything你需要在一個文件中,這是我生活中寫過的最無效的代碼,但它解決了我們的問題! – 2016-08-23 01:58:18

2

可能爲時已晚來回答題。但是我遇到了同樣的問題。我用「JSON_PRETTY_PRINT」

以下是我的代碼解決它:

<?php 

if(isset($_POST['object'])) { 
    $json = json_encode($_POST['object'],JSON_PRETTY_PRINT); 
    $fp = fopen('results.json', 'w'); 
    fwrite($fp, $json); 
    fclose($fp); 
} else { 
    echo "Object Not Received"; 
} 
?>