簡體   English   中英

將JSON對象寫入服務器上的.json文件

[英]writing JSON object to .json file on server

我正在嘗試將我的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
    } ,

知道為什么我得到所有這些斜線以及為什么它都在一條線上?

謝謝,Hristo

你是雙重編碼。 不需要在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 
   }
?>

不要JSON.stringify 這樣做可以獲得雙JSON編碼。

首先將數組元素轉換為JSON字符串,然后將它們添加到完整對象,然后對大對象進行編碼,但在編碼時,已編碼的元素將被視為簡單字符串,以便對所有特殊字符進行轉義。 你需要有一個大對象並只編碼一次。 編碼器將照顧孩子。

對於on row問題,嘗試發送一個JSON數據類型標題: Content-type: text/json我認為(沒有google for it)。 但渲染僅取決於您的瀏覽器。 也可以用縮進編碼。

回答這個問題可能為時已晚。 但我遇到了同樣的問題。 我通過使用“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";
}
?>
<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"
  }
    ]
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM