代码之家  ›  专栏  ›  技术社区  ›  Hristo

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

  •  6
  • Hristo  · 技术社区  · 15 年前

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

    4 回复  |  直到 7 年前
        1
  •  20
  •   Tomalak    10 年前

    你是双重编码。不需要在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 
       }
    ?>
    
        2
  •  5
  •   Alin P.    15 年前

    不要 JSON.stringify

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

    对于行内问题,请尝试发送JSON数据类型头: Content-type: text/json 我想(不是谷歌搜索的)。但是渲染将只取决于您的浏览器。也可以使用缩进进行编码。

        3
  •  2
  •   Suveer Jacob    10 年前

    以下是我的代码:

    <?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";
    }
    ?>
    
        4
  •  0
  •   sudheer    10 年前
    <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>
    

    数据.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"
      }
        ]
      }