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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 将JSON对象写入服务器上的.json文件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将我的 JSON对象写入服务器上的.json文件.我现@L_360_2@样做的方式是:

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
    },

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

谢谢,
斯托伊奇

你是双重编码.不需要在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",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 
   }
?>

脚本宝典总结

以上是脚本宝典为你收集整理的php – 将JSON对象写入服务器上的.json文件全部内容,希望文章能够帮你解决php – 将JSON对象写入服务器上的.json文件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。