Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing JSON object to .json file on server

I'm trying to write my JSON object to a .json file on the server. The way I'm doing this now is:

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);
?>

It is writing fine and the information seems to be correct, but it is not rendering properly. It is coming out as:

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

... but I'm expecting this:

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

Why am I getting all of these slashes and why it is all on one line?

like image 654
Hristo Avatar asked Oct 13 '10 07:10

Hristo


People also ask

How do I post JSON to the server?

To post JSON data to the server, we need to use the HTTP POST request method and set the correct MIME type for the body. The correct MIME type for JSON is application/json. In this POST JSON example, the Content-Type: application/json request header specifies the media type for the resource in the body.

How do I make a JSON file?

Steps to open JSON files on Web browser (Chrome, Mozilla)Open the Web store on your web browser using the apps option menu or directly using this link. Here, type JSON View in search bar under the Extensions category. You will get the various extensions similar to JSON View to open the JSON format files.


3 Answers

Probably too late to answer the question. But I encountered the same issue. I resolved it by using "JSON_PRETTY_PRINT"

Following is my code:

<?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";
}
?>
like image 117
Suveer Jacob Avatar answered Oct 11 '22 10:10

Suveer Jacob


You are double-encoding. There is no need to encode in JS and PHP, just do it on one side, and just do it once.

// 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)
    }
});

Note that the dataType parameter denotes the expected response type, not the the type you send the data as. Post requests will be sent as application/x-www-form-urlencoded by default.

I don't think you need that parameter at all. You could trim that down to:

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

Then (in PHP) do:

<?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 
   }
?>
like image 41
Tomalak Avatar answered Oct 11 '22 09:10

Tomalak


Don't JSON.stringify. You get a double JSON encoding by doing that.

You first convert your array elements to a JSON string, then you add them to your full object, and then you encode your big object, but when encoding the elements already encoded are treated as simple strings so all the special chars are escaped. You need to have one big object and encode it just once. The encoder will take care of the children.

For the on row problem try sending a JSON data type header: Content-type: text/json I think (didn't google for it). But rendering will depend only on your browser. Also it may be possible to encode with indentation.

like image 27
Alin Purcaru Avatar answered Oct 11 '22 08:10

Alin Purcaru