将JSON对象写入服务器上的.json文件

Hri*_*sto 8 javascript php ajax json writefile

我正在尝试将我的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
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

PHP:

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

   $file = fopen('new_map_data.json','w+');
   fwrite($file, $info);
   fclose($file);
?>
Run Code Online (Sandbox Code Playgroud)

它写得很好,信息似乎是正确的,但它没有正确呈现.它出现了:

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

......但我期待这个:

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

知道为什么我得到所有这些斜线以及为什么它都在一条线上?

谢谢,Hristo

Tom*_*lak 19

你是双重编码.不需要在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)
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,该dataType参数表示预期的响应类型,而不是您将数据发送的类型.发布请求将application/x-www-form-urlencoded默认发送.

我认为你根本不需要那个参数.您可以将其减少到:

$.post("json.php", {json : JSON.stringify(data)});
Run Code Online (Sandbox Code Playgroud)

然后(在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 
   }
?>
Run Code Online (Sandbox Code Playgroud)


Ali*_*aru 5

不要JSON.stringify.这样做可以获得双JSON编码.

首先将数组元素转换为JSON字符串,然后将它们添加到完整对象,然后对大对象进行编码,但在编码时,已编码的元素将被视为简单字符串,以便对所有特殊字符进行转义.你需要有一个大对象并只编码一次.编码器将照顾孩子.

对于行上的问题,尝试发送一个JSON数据类型标题:Content-type: text/json我认为(没有谷歌为它).但渲染仅取决于您的浏览器.也可以用缩进编码.