Nodejs write json to a file - json

I just started learning nodejs. I am currently working with sockets and made chat program.
I want to save entire chat to a json file. Currently my code is this :
socket.on('chat', function (data) {
message = {user : data.message.user, message : data.message.message};
chat_room.sockets.emit('chat', {message: message});
jsonString = JSON.stringify(message);
fs.appendFile("public/chat.json", jsonString, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
This is currently working perfect, but the json which is written in file is wrong.
This gave me a wrong json
{"user":"niraj","message":"hw r u?"}{"user":"ntechi","message":"hello"}{"user":"ntechi","message":"hw r u?"}
The above code is called when message is triggered. I want json in this format
{"user":"awd","message":"hw r u?","user":"ntechi","message":"hello","user":"ntechi","message":"hw r u?"}
Can anyone help me in this? Thanks in advance

The first set of wrong JSON is created because you are appending a piece of JSON to a file each time you get a message.
The second set of JSON is also wrong - each property name has to be unique.
Presumably you want something like:
[
{"user":"niraj","message":"hw r u?"},
{"user":"ntechi","message":"hello"},
{"user":"ntechi","message":"hw r u?"}
]
In which case the logic you need to use is:
Read data from file
Parse data as JSON and assign to a variable
In the event of an error, assign an empty array to that variable
push the message object onto the end of the array
stringify the array
Overwrite the file with the new string

Related

How to load json file?

I am just trying to load JSON file into my react project. I did it like this:
fetch(dane).then(response => {
console.log(response);
return response.json();
}).then(dane => {
console.log(dane);
}).catch(err => {
console.log("Error Reading data " + err);
});
and I imported this file into project:
import data from "./data.json";
but I am getting error like this:Unexpected token < in JSON at position 0
How can I fix it?
If I am asking about something very stupid, just sorry.
The json file is in src folder.
You would only use fetch to get the data from an API and assign the response to a variable that you can call.
Since you are using a mock json response stored in a file, you can do the following.
Example:
A file called data.json containing the following.
{
"name": "John",
"age": "47",
"role": "admin"
}
Can be imported via:
import data from "./data.json"
Then used in your component however you wish.
<h1>Hello {data.name}.</h1>
<h2>Logged in as: {data.role}</h2>
Or if used outside of the render, like in a function:
console.log(data.role)
Also, Unexpected token < in JSON at position 0 seems like your JSON is improperly formatted.
The JSON file should only contain valid JSON data, as shown in my basic example above.

React.js: setState method setting variable to a string instead of object... is there a workaround?

I am trying to fetch a simple JSON element from express.js. I am trying have React assign it to a state variable on the front end. I am using this code to do so:
componentDidMount() {
fetch("/user")
.then(response => response.json())
.then(result => this.setState({myUser:result}))
}
But when I run typeof myUser after this setState command, it says string instead of object. I've tried using JSON.parse(), etc. But either I get an error or it continues to assign the data as a string rather than JSON. What sort of syntax do I need to use in this fetch-then context to coerce the data assignment to be JSON?
I have read this link:
With this code:
componentDidMount(){
fetch('https://abx.com/data/tool.json').then(response =>{
if (!response.ok) throw Error('Response not ok')
return response.json(); // This is built in JSON.parse wrapped as a Promise
}).then(json => {
this.setState({"sections" : json});
}).catch(err =>{
console.log(err);
});
}
But it doesn't solve the problem. I ran this code directly in my application verbatim. When I run typeof on the variable, it says string instead of object. I looked at other posts on Stack Overflow, but I did not see a solution to this.
I figured out what was going wrong (after many hours of experimenting):
On the server side, I was creating a "homegrown" JSON object using string and variable concatenation. I also tried creating the JSON object by doing this:
var str = "name:" + name + ", department:" + department
var user = {str};
Both of these were not working in subtle ways... despite trying different types of gadgetry on the client side, I couldn't get React to interpret the data as a JSON object. But then I had an idea to construct the JSON on the server side (in Express.js) like this:
var user = {};
user["name"] = name;
user["department"] = department;
That immediately cleared things up on the server side and the client side. When using setState() in React, it now sets the value as an object (which was the goal all along).
I think this can be useful to others... if React doesn't seem to understand the JSON, perhaps it is being sent from the server in a subtly incorrect format.

Json File Creation in nodeJS

I need to create a JSON file in the below format in nodeJS also i need to traverse into the particular position and add the values if any. I have done it in Java, but no idea in NodeJs. It will be helpful if someone helps me. Thanks.
If my understanding is correct, you are using Protractor to automate AngularJS tests and write the results as JSON for reporting / for parsing it back once done?
If that's the case, you could simply store the results as a Object in Javascript and write it out using fs node package.
Writing the JSON Report file
var fs = require('fs');
//..Protractor .. and other logic..
var results = { Project : "xxx" , ....};
//...more of that assignment....
//You could use JSON.parse() or JSON.stringify() to read/convert this object to string vice versa and fs package to read/write it to file.
fs.writeFile("/tmp/testreport.json", JSON.stringify(results), function(err) {
if(err) {
return console.log(err);
}
console.log("The test report file was saved as JSON file!");
});

Having trouble retrieving JSON from res

I'm using node, express, and mongoose.
I have a function that performs a search in a database and sends the response in a JSON format with:
res.jsonp(search_result);
This displays the correctly returned result in the browser as a JSON object. My question is, how do I get that JSON object?
I've tried returning search_result but that gives me null (possibly because asynchronous). I'd also like to not edit the current function (it was written by someone else). I'm calling the function and getting a screen full of JSON, which is what res.jsonp is supposed to do.
Thanks in advance.
Just make a new function that takes this JSON as parameter and place it inside the old one. Example:
// Old function
app.get('/', function(req,res){
// recieve json
json_object = .....
// Get json to your function
processJson(json_object);
// Old function stuff
.
.
.
});
function processJson(json_object) {
// Here you'll have the existing object and can process it
json_object...
}

JSON call error with d3js

I'm trying to replicate this example of a bar chart that transitions in d3js. However, when I input my data into the .json file I get the error "Cannot call method 'forEach' of undefined" so I'm pretty sure I'm calling the .json file incorrectly. I have correctly changed the names of my variables, which are dates instead of text, so maybe that's messing something up:
Here's my .json file:
[{"network":"ABC","2002":9860,"2003":10596,"2004":9989,"2005":12217,"2006":12281,"2007":11913,"2008":12265,"2009":11050,"2010":9595,"2011":9871,"2012":8339},
{"network":"AZA","2002":0,"2003":0,"2004":0,"2005":0,"2006":213,"2007":0,"2008":0,"2009":201,"2010":236,"2011":212,"2012":0},
{"network":"CBS","2002":13959,"2003":13856,"2004":13581,"2005":12843,"2006":13019,"2007":11726,"2008":11274,"2009":11812,"2010":12538,"2011":12284,"2012":10690}]
And how I've tried to call it:
var json
d3.json("data.json", function(error, result){
json = result;
var data = [];
json.forEach(function(d){
data.push({variable: +d['2002'], network: d['network']});
});
x.domain(data.map(function(d) { return d.network; }));
y.domain([d3.min(data, function(d) { return d.variable; }), d3.max(data, function(d) { return d.variable; })]);
Any help would be much appreciated!
Your D3js code does not have any error.May be the json file is unreachable(as per the code the json file should reside in same folder of the HTML file).
You can use "console.log(json);" just after the line "json = result;" if the data is read from the file u will find it in console of "FireBug" or "Developer tools"(in chrome)
You might have an older version of D3 than in the example. I ran into the same problem and found that my version of D3 did not have an error parameter on the json function so the first parameter passed (the error, which was null) was expected to be the JSON string. So the 2 solutions I found are:
(1) Switch the parameters to have the JSON first:
d3.json("data.json", function(result, error){ ...
or just remove the error parameter altogether.
(2) Update to d3.v3.js.
Thanks for the reporting this question ,
Your error is because of your json file is unreachable.