Viewed   67 times

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?

 Answers

2

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 
   }
?>
Wednesday, October 5, 2022
 
1

Your quick solution would be:

$("#select_coffee_talk_year").button().click(function() {
    var form = $('#coffee_talk_year');  
    var data = form.serialize();

    $.ajax({
        url: "include/scripts/select_event.php",
        type: "POST",
        data: data,
        dataType: 'json',
        success: function (select) {
            var coffee_talk = $("#coffee_talk");
            coffee_talk.fadeOut('fast', function() {
                for(i in select) {
                    row = select[i];
                    div = coffee_talk.append('<div id="row_'+i+'" />');
                    for(column in row) {
                       div.append('<span class="column_'+column+'">'+row[column]+'</span>');
                    }
                }
                coffee_talk.fadeIn();
            });
        }   
    });
    return false;
});

For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).

It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.

Friday, November 4, 2022
 
abhinav
 
1

You're taking a JSON string and pretending that it's a Javascript object literal. But, remember, JSON is merely named after Javascript's object notation!

You're then hoping that eval will directly evaluate this and return an object, but this is not the case.


Observations

Writing the following in the Firebug console:

eval('{"caption":"A caption","filename":"myimage_thumb.jpg"}')

will also yield a SyntaxError. (Ideally, you'd have narrowed your problem down to this!)

Interestingly, constructing an object more explicitly does work (for this input):

eval('new Object({"caption":"A caption","filename":"myimage_thumb.jpg"})')

As does just forcing the input into being a certain kind of expression, with parentheses:

eval('({"caption":"A caption","filename":"myimage_thumb.jpg"})')

Explanation

It all comes down to this statement from 12.4 in the ECMAScript standard:

Note that an ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block.

This article explains the issue in depth, but in summary the solution is to use JSON.parse(res) to obtain an object from a JSON string. This is the proper approach, and it will not fail as long as your input is valid JSON.

Monday, August 8, 2022
 
ajp
 
ajp
1
sed -i '$s/}/,n"location":"canada"}/' sample.json

Result:

{"name" :"sam",
"age":23,
"designation":"doctor",
"location":"canada"}
Saturday, September 17, 2022
 
5

You need to stringify the object.

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));
Sunday, August 28, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :