Writing JSON object to .json file on server
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
}
?>
Write / add data in JSON file using Node.js
If this JSON file won't become too big over time, you should try:
Create a JavaScript object with the table array in it
var obj = {
table: []
};Add some data to it, for example:
obj.table.push({id: 1, square:2});
Convert it from an object to a string with
JSON.stringify
var json = JSON.stringify(obj);
Use fs to write the file to disk
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);If you want to append it, read the JSON file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.
UPDATE:
Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.
How to write data to a JSON file using Javascript
You have to be clear on what you mean by "JSON".
Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]
. This one happens to be an array. If you want to add a new element to the array, just push
it, as in
var arr = [{a: 1}];
arr.push({b: 2});
< [{a: 1}, {b: 2}]
The word JSON may also be used to refer to a string which is encoded in JSON format:
var json = '[{"a": 1}]';
Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse
:
var obj = JSON.parse(json);
Now you can manipulate the object any way you want, including push
as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify
:
var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'
JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse
it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify
, and use another ajax call to send the data to the server for storage or other manipulation.
You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.
Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?
Writing JSON object to .json file on server
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
}
?>
Convert a json file from server body to a json object in node
First of all, the example you provided (where each line is a string representing a JSON object) is not a JSON file.
It’s a file containing multiple JSON formatted strings, one per line.
Without a surrounding array, it is no wonder you cannot parse it.
I’m also unsure what you mean by the data being kept in a buffer.
Do you mean that you’ve read the contents of the file using the standard fs.readfile()
or variant?
If this is the case, you need to convert the Buffer
returned from your readfile to a String
, as in:
var contents = fs.readfileSync(FILEPATH).toString()
Once you have done so, you could construct an Array using the contents of your file and convert the result to a JSON formatted string using:
fs.readfile(FILEPATH, (err, buf) => {
if (err) {
throw err
}
let objAry = []
buf.toString().split(/\r?\n/).forEach( line => {
objAry.push(JSON.parse(line))
})
let jsonStr = JSON.stringify(objAry)
// do something with the result string
// possibly sending it as a response to an API
// request as ‘Content-Type: application/json’
})
Obviously, you’ll want to add error handling (try/catch) to this.
Writing JSON object to a JSON file with fs.writeFileSync
You need to stringify the object.
fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));
How do I save JSON to local text file
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
Related Topics
Does PHP's $_Request Method Have a Security Problem
At' Symbol Before Variable Name in PHP: @$_Post
How to Decode Numeric HTML Entities in PHP
Get Only Filename from Url in PHP Without Any Variable Values Which Exist in the Url
How to Format Messages for Queueing
Preg_Replace with Array Replacements
Query MySQL and Export Data as CSV in PHP
Use PHP to Display MySQL Results in HTML Table
Check If a File Was Included or Loaded
Large Hex Values with PHP Hexdec
Using Print_R and Var_Dump with Circular Reference
Pdo Catch and Output MySQL Errors
Array_Push() VS. $Array[] = .... Which Is Fastest
Is It Really That Wrong Not Using Setters and Getters
How to Install Gd on My Windows Server Version of PHP
Inheritance of Static Members in PHP
Randomly Losing Session Variables Only in Google Chrome & Url Rewriting