I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).
Related
Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: [] Example:
[
{"name":"jhon"},
{"name":"jhonathan"}
]
Here is the code:
Thanks.
The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.
The thing is, when you call fs.appendFile, you're only writing to the end of the file. You're not following JSON format by doing so.
You need to do this:
Read file content.
Parse JSON text into an object.
Update the object in memory.
Write object in JSON format back to the file system.
I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.
const path = __dirname + 'db.json'
// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)
// Add new item to the item list
items.push(newItem)
// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)
I'm trying to write data into an Excel file using ExcelJS library. I was successfully able to create worksheet and add column data.
However, while trying to implement addRow() or addRows() method, the data is not added into the Excel worksheet.
Here is the code I tried:
const ExcelJS = require('exceljs');
var workbook = new ExcelJS.Workbook();
var worksheet = workbook.addWorksheet('Payment Data');
worksheet.columns = reportHeaders; //reportHeaders is an array of header objects
I'm able to see the columns created successfully in the excel sheet. The trouble starts from below, where I'm trying to add data (into rows):
1st method :
worksheet.addRows(excelData);//excelData is an array of data objects
2nd method:
for(var rowItem in excelData){
worksheet.addRow(excelData[rowItem]);}
However, it seems either of these methods aren't working for me.
Finally, the file is saved:
workbook.xlsx.writeFile('PaymentData.xlsx')
Is there anything I'm missing? Any help will be appreciated.
So the issue with your code was, you were trying to add the data to the columns without specifying the key property in the columns array and hence it was unable to add the data.
I modified the worksheet.columns array to look something like the following:
worksheet.columns = [
{ header: "A", key: "a" },
{ header: "B", key: "b" },
];
This will solve your problem
I managed to convert the object to an array and passed it to the addRow method.
This worked for me.
I'm still not sure why I'm not able to pass an array of objects to addRow method.
This is my main JSON file
{
"chartType" : ["column", "column", "pie"],
"chartTitle": ["Cantidad de equipos", "Cantidad de artículos consumibles","Cantidad de empleados a cargo"],
"yAxisTitle": ["Equipos", "Consumibles", "Empleados"],
"seriesName": ["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"],
"seriesData": ["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"]
}
That loads others PHP JSON_ENCODE files in "seriesName" and "seriesData".
These JSON results generate keys "id" and "nombre" (spanish word for name).
How read values for these keys through Angular Service $http.get of the main JSON?
**UPDATE (06/03/2016)**
I'm middle of road!
I read the JSON objects from "seriesName" array with angular.fromJson function as follow:
var deserialize = angular.FromJson(data);
var objects = deserialize.seriesName;
console.log(objects);
That's throws me an array of objects:
["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"]
Thus, how I could read the objects contained in these URL's through Angular?
First of all you need to decode the JSON in PHP using json_decode(), then you treat the result as an object.
Try something like;
$data = xyz; // pass in the JSON object
$res = json_decode($data); // decode JSON
$chartType = $res->chartType; // access property as an object
You can also try var_dump($res) to get a clearer understanding of the structure and how to access it;
You can do following.
$http.get('url_to_json').then(fucntion(response) {
var myJson = response.data;
var keys = Object.keys(myJson);
console.log('Your keys', keys);
}, fucntion(error) {
});
Altough have button, I could resolve this issue.
I have created a repository that integrates Angular.js, PHP, and Highcharts, with Materialize.css, adding series dynamically from external JSON.
link: https://github.com/Nullises/DynamicSeriesHighchartsAngular
I'm using node-soap with a service and everything works but I need to send an array of ints and I find that I can only send the first one because I can't find the correct way to build a JS object to represent this array.
I've been looking at similar questions but I couldn't find the answer to my question.
I need to generate a XML property like the following one:
<ns1:ArrayOfInts>
<!--Zero or more repetitions:-->
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:ArrayOfInts>
by passing an object that contains the array:
soapObject = {
somefields,
"ns1:ArrayOfInts": {
Something goes here
},
};
Any idea how to create the JS object?
I had the same problem and used $xml property to add raw XML to the request and attributes to set the arr namespace:
var fields = [2904, 3089, 4531];
soapObject.arrayOfInts = {
attributes: {
'xmlns:arr': 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'
},
$xml: fields.map(function(value) {
return '<arr:int>' + value + '</arr:int>';
}).join('')
};
This code will generate the following request:
<ns1:arrayOfInts xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:arrayOfInts>
Hi i am a new bee to sails and trying to get a model api that finally gives output as follows
[
{
"icon" : [
{"name":"ico1", "ico_typ":"fb", "ico_content_URL":"someLocation"},
{"name":"ico2", "ico_typ":"tw", "ico_content_URL":"someLocation"},
{...}
]
"createdAt":
"updatedAt":
}
]
I thought i can achieve this by passing the icon attribute as an Array but the problem is it passes the whole Array as string when i load it in REST CLIENT also i could not use the validation for values inside Array like without ico_type and URL the data should not be loaded into database. So, any suggestion about use of the 'array' where i'm wrong is very appreciated, thanks so much!
Sails_v0.11.0
MongoDB_3.0.1
In your model define a method
toJSON: function () {
var obj = this.toObject();
//say your obj.icon returns something like `'[{"name":"ico1","ico_typ":"fb","ico_content_URL":"someLocation"},{"name":"ico2","ico_typ":"tw","ico_content_URL":"someLocation"}]'`
obj.icon = JSON.parse(obj.icon)
return obj;
},
I think the model WaterLine gave you is already an JSON format, all you need to do is to use the right way to response it.
res.json(model);