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

前端之家收集整理的这篇文章主要介绍了php – 将JSON对象写入服务器上的.json文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将我的 JSON对象写入服务器上的.json文件.我现在这样做的方式是:

JavaScript的:

  1. function createJsonFile() {
  2.  
  3. var jsonObject = {
  4. "metros" : [],"routes" : []
  5. };
  6.  
  7. // write cities to JSON Object
  8. for ( var index = 0; index < graph.getVerticies().length; index++) {
  9. jsonObject.metros[index] = JSON.stringify(graph.getVertex(index).getData());
  10. }
  11.  
  12. // write routes to JSON Object
  13. for ( var index = 0; index < graph.getEdges().length; index++) {
  14. jsonObject.routes[index] = JSON.stringify(graph.getEdge(index));
  15. }
  16.  
  17. // some jQuery to write to file
  18. $.ajax({
  19. type : "POST",url : "json.PHP",dataType : 'json',data : {
  20. json : jsonObject
  21. }
  22. });
  23. };

PHP

  1. <?PHP
  2. $json = $_POST['json'];
  3. $info = json_encode($json);
  4.  
  5. $file = fopen('new_map_data.json','w+');
  6. fwrite($file,$info);
  7. fclose($file);
  8. ?>

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

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

……但我期待这个:

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

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

谢谢,
斯托伊奇

你是双重编码.不需要在JS和PHP中进行编码,只需在一侧进行编码,只需执行一次即可.
  1. // step 1: build data structure
  2. var data = {
  3. metros: graph.getVerticies(),routes: graph.getEdges()
  4. }
  5.  
  6. // step 2: convert data structure to JSON
  7. $.ajax({
  8. type : "POST",data : {
  9. json : JSON.stringify(data)
  10. }
  11. });

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

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

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

然后(在PHP中)做:

  1. <?PHP
  2. $json = $_POST['json'];
  3.  
  4. /* sanity check */
  5. if (json_decode($json) != null)
  6. {
  7. $file = fopen('new_map_data.json','w+');
  8. fwrite($file,$json);
  9. fclose($file);
  10. }
  11. else
  12. {
  13. // user has posted invalid JSON,handle the error
  14. }
  15. ?>

猜你在找的PHP相关文章