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

11
我想将我的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
    } ,

为什么我会得到这么多斜杠,而且它们都在同一行?


你是否在使用框架或在POST之前进行任何过滤?尝试在php.ini中关闭magic_quotes并重新启动。 - RobertPitt
4个回答

21

你进行了双重编码。没有必要在JavaScript 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参数表示预期的响应类型,而不是您发送数据的类型。默认情况下,POST请求将被发送为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 
   }
?>

难道不应该是 fwrite($file, $json); 吗? - Francesco

5
不要使用JSON.stringify,这样做会导致双重 JSON 编码。
首先,您将数组元素转换为 JSON 字符串,然后将它们添加到完整对象中,最后对大对象进行编码。但是,在对已经编码的元素进行再次编码时,它们被视为简单字符串,因此所有特殊字符都被转义。您需要有一个大对象,只需对其进行一次编码即可。编码器会处理子级。
对于行内问题,请尝试发送一个 JSON 数据类型的标题:Content-type: text/json(我没有搜索)。但呈现仅取决于您的浏览器。还可以可能编码缩进。

我猜那个方法可行... 我原以为需要使用 JSON.stringify 来正确格式化我的对象?我为我的对象定义了一个 toJSON 函数,所以我才使用 stringify。我把它拿掉了,就没有出现 \\ 了,但是它仍然在一行上... - Hristo
@Hristo:所有的内容都在一行上有什么问题吗?我认为你不必担心。 - Tomalak
他可能需要在开发过程中检查一下,这可能会对他有所帮助。如果只是用于存储,那就没什么问题。 - Alin Purcaru
1
http://www.jsonlint.com/比直接扫描格式化的字符串更好。 - Tomalak

4

可能已经太晚回答这个问题了,但我遇到了同样的问题。我使用了"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";
}
?>

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"
  }
    ]
  }

所有你需要的东西都在一个文件里,这是我人生中写过的最低效的代码,但它解决了你的问题! - sudheer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接