Confused on how notes = JSON.parse(noteString); - json

var addnote = function (title, body) {
var notes = [];
var note = {
title: title,
body: body
}
need explanation on the two lines under try
try {
var noteString = fs.readFileSync("data.json");
notes = JSON.parse(noteString);
} catch (e) {
}
And explanation on how duplicateNotes works ..
var duplicateNotes = notes.filter(function(note){
return note.title === title
})
if (duplicateNotes.length === 0) {
notes.push(note);
fs.writeFileSync("data.json", JSON.stringify(notes));
}
}

JSON.parse converts a JSON object to String.
{
field1:field1Value,
field2:fieldValue
}
If this is in Json format you can access it's elements using JSONObjectName.fieldName
But,if it's converted to String it looses it's JSON properties. You can't access fields in same way. Output will act like String.
need explanation on the two lines under try
var noteString = fs.readFileSync("data.json");
There are two kinds of response back asynchronous and synchronous. Synchronous call is like you will not start playing until you get a pass and score a goal. But, Asynchronous call is like you start playing with your friend but, you run near him and, there is a promise you won't shoot until you get the ball.
readFileSync will read the file and the next line will wait until it gets the pass.JSON.parse() will convert file content to JSON object.
And explanation on how duplicateNotes works ..
var duplicateNotes = notes.filter(function(note){
return note.title === title
})
Whenever a match is found , that element in notes will be pushed to duplicate note. That's all.

Related

Turn JSON Data Into Int To Perform Calculations

Trying to convert JSON data into int in order to perform calculations, multiply by numbers or percentages (or whichever method is best recommended)
Tried performing calculation on the object (using addition for example), but it only added numbers on to the end of the resulting string. I have seen suggestions on using JSON parse (reviver) but can't seem to get my head round getting the desired data when it is only one specific part of the JSON data required rather than multiple items of data from the JSON link.
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var gbpValue = "1 BTC equals to £" + json["bpi"]["GBP"]["rate"];
document.getElementById("data").innerHTML =
gbpValue;
As mentioned, have tried performing calculations on the result but it only adds numbers to the end of the string. Thanks for any advice or help.
What I can see in your code is that you are adding your json variable with a string which would always result in string concatenation in below line:
var gbpValue = "1 BTC equals to £" + json["bpi"]["GBP"]["rate"];
First check your json object if it a number or string.
You could use the Number() or parseInt() functions to convert a string to number.
Example:
var num=Number("23");
or
var num=parseInt("23");
Hope it helps. :)

MEAN Nodejs JSON.parse passing data from client to server

I am using MEAN stack and I am sending query parameters dynamically to my Nodejs server endpoints.
My client controller :
$http.get('/api/things',{params:{query:query}}).then(response => {
this.awesomeThings = response.data;
socket.syncUpdates('thing', this.awesomeThings);
});
where query is a value injected into the controller.
This is the server controller function (which works):
export function index(req, res) {
var query = req.query.query && JSON.parse(req.query.query)
Thing.find(query).sort({_id:-1}).limit(20).execAsync()
.then(respondWithResult(res))
.catch(handleError(res));
}
The above works but I am trying to understand the line
var query = req.query.query && JSON.parse(req.query.query)
as I have never seen this before( and I don't come from a programming background). I console.logged query and understand it's an object (which is required by Mongodb) but when I console.logged (JSON.parse(req.query.query)) or JSON.parse(query) to find out the final output, the program stops working with no error messages, very strange..
If someone can explain the above syntax and why it has to be done this way for it work, that would be much appreciated..
PS when I try to console log the JSON.parse like so, it fails to load even though it should have no effect whatsoever:
export function index(req, res) {
var query = req.query.query && JSON.parse(req.query.query)
var que = JSON.parse(req.query.query)
Thing.find(query).sort({_id:-1}).limit(20).execAsync()
.then(respondWithResult(res))
.catch(handleError(res));
console.log("que"+que)
}
function one() {
var x = {};
var res = JSON.parse(x.y);
console.log(res);
}
function two() {
var x = {};
var res = x.y && JSON.parse(x.y);
console.log(res);
}
<button onclick="one()">ERROR</button>
<button onclick="two()">NO ERROR</button>
var x = data && JSON.parse(data);
Since expression is evaluated from left, first data is evaulated.
If it is undefined then, the next part -> JSON.parse() is not performed.
On the other hand, if data is defined parse is tried and the result is returned and stored in x.
Main advantage here is the parse doesn't run if the variable wasn't defined.
it could be equivalent to saying:
if(data) {x = JSON.parse(x);}

Printing parsed JSON

So, I've parsed a response like this:
var g_rgListingInfo = JSON.parse( response );
response looks like this
{"321242653847396921":{"listingid":"321242653847396921","price":28338,"fee":4249,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2003","steam_fee":1416,"publisher_fee":2833,"asset":{"currency":0,"appid":730,"contextid":"2","id":"3038615825","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"321242653843485871":{"listingid":"321242653843485871","price":30175,"fee":4525,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2003","steam_fee":1508,"publisher_fee":3017,"asset":{"currency":0,"appid":730,"contextid":"2","id":"1730491611","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"782860982384213986":{"listingid":"782860982384213986","price":31305,"fee":4695,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2003","steam_fee":1565,"publisher_fee":3130,"asset":{"currency":0,"appid":730,"contextid":"2","id":"2815962367","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"783987515556891867":{"listingid":"783987515556891867","price":31305,"fee":4695,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2003","steam_fee":1565,"publisher_fee":3130,"asset":{"currency":0,"appid":730,"contextid":"2","id":"3708699202","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"783987515558623437":{"listingid":"783987515558623437","price":30957,"fee":4642,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2003","steam_fee":1547,"publisher_fee":3095,"asset":{"currency":0,"appid":730,"contextid":"2","id":"4462433815","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"718685320959305952":{"listingid":"718685320959305952","price":34000,"fee":5100,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2001","steam_fee":1700,"publisher_fee":3400,"asset":{"currency":0,"appid":730,"contextid":"2","id":"4450043953","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"796369492002647568":{"listingid":"796369492002647568","price":34500,"fee":5175,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2001","steam_fee":1725,"publisher_fee":3450,"asset":{"currency":0,"appid":730,"contextid":"2","id":"4024113558","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D3082226233578562378","name":"Inspect in Game..."}]}},"718684619833530742":{"listingid":"718684619833530742","price":22958,"fee":3442,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2002","steam_fee":1147,"publisher_fee":2295,"asset":{"currency":0,"appid":730,"contextid":"2","id":"4331886445","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"788487401257494747":{"listingid":"788487401257494747","price":34783,"fee":5217,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2001","steam_fee":1739,"publisher_fee":3478,"asset":{"currency":0,"appid":730,"contextid":"2","id":"2315637005","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D1030942533801731526","name":"Inspect in Game..."}]}},"321242020664839911":{"listingid":"321242020664839911","price":34783,"fee":5217,"publisher_fee_app":730,"publisher_fee_percent":"0.10000000149011612","currencyid":"2001","steam_fee":1739,"publisher_fee":3478,"asset":{"currency":0,"appid":730,"contextid":"2","id":"4283078084","amount":"1","market_actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D6944696178921031564","name":"Inspect in Game..."}]}}}
I put it in here: http://json.parser.online.fr/ this is the
result
The problem I'm having is that I fail to loop through the items. g_rgListingInfo.length is NaN. I tried to use forEach but that failed too.
I want to loop through all these "321242653847396921", "321242653843485871"... wich are always changing and obtain their listingid, price, fee etc.
I am pretty new to node.js so I'm sorry if this is a stupid question.
You have an object, not an array. So, to iterate the results, you have to either convert your object into an array or just iterate it as object.
Converting into array
Depending on what you need, this could be more convenient:
var myData = Object.keys(g_rgListingInfo).map(Number).sort().map(function (c) {
return g_rgListingInfo[c];
});
// Then you can just use the `myData` array
myData.forEach(function (current, index) {
/* do something */
});
// ...or using for loop
for (var i = 0; i < myData.length; ++i) {
var current = myData[i];
/* do something */
}
Iterating the object
You have to get the keys of the object iterate them (optionally you maybe want to sort them first).
// ["3124...", ...]
var numbers = Object.keys(g_rgListingInfo);
// Optional sort
numbers = numbers.map(Number).sort();
// Iterate the object keys
numbers.forEach(function (currentKey) {
var currentObject = g_rgListingInfo[currentKey];
});

Select specific data in JSON output

I've created a function that does a http request and then saves some data from the JSON output.
$scope.addMovie = function() {
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
// $scope.movieListID = data.results;
$scope.movieListID = data;
console.log($scope.movieListID);
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path
}).then(init);
} else {
console.error('Error happened while getting the movie list.')
}
})
};
This function saves the title, release date en posterpath and that works fine. The problem is that it only saves one release_date while the JSON output has a lot more, but I don't know how to acces that.
This is a example of the JSON output I request
It has a release_date, which I save now, but it also has more information,
releases":{
"countries":[
{"certification":"","iso_3166_1":"GB","primary":true,"release_date":"2015-10-26"},
{"certification":"","iso_3166_1":"US","primary":false,"release_date":"2015-11-06"},
{"certification":"","iso_3166_1":"NL","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"BR","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"SE","primary":false,"release_date":"2015-11-04"},
{"certification":"","iso_3166_1":"IE","primary":false,"release_date":"2015-10-26"},
How would I go about saving the release date for the NL release?
You just need to iterate through the countries array, and check if the country code matches the one you wish to retrieve. For your example with 'NL':
var releaseNL;
for (var i = 0; i < $scope.movieList.releases.countries.length; i++) {
var release = $scope.movieList.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
This is just one of many ways to do this (e.g. you could use angular.forEach, wrap it inside a function, etc.), but this should give you an idea.
Remark: I noticed you have been asking a lot of very basic questions today, which you could easily answer yourself with a bit more research. E.g. this question is not even AngularJS related, but just a simple JavaScript task. So maybe try to show a bit more initiative next time! ;)

Trying to interpret the Node-Neo4j API

I'm pretty new to coding so forgive me if my code is unreadable or my question simplistic.
I am trying to create a little server application that (amongst other things) displays the properties of a neo4j node. I am using node.js, Express and Aseem Kishore's Node-Neo4j REST API client, the documentation for which can be found here.
My question stems from my inability to fetch the properties of nodes and paths. I can return a node or path, but they seem to be full of objects with which I cannot interact. I poured through the API documents looking for some examples of how particular methods are called but I found nothing.
Ive been trying to call the #toJSON method like, "db.toJSON(neoNode);" but it tells me that db does not contain that method. I've also tried, "var x = neoNode.data" but it returns undefined.
Could someone please help me figure this out?
//This file accepts POST data to the "queryanode" module
//and sends it to "talkToNeo" which queries the neo4j database.
//The results are sent to "resultants" where they are posted to
//a Jade view. Unfortuantly, the data comes out looking like
// [object Object] or a huge long string, or simply undefined.
var neo4j = require('neo4j');
var db = new neo4j.GraphDatabase('http://localhost:7474');
function resultants(neoNode, res){
// if I console.log(neoNode) here, I now get the 4 digit integer
// that Neo4j uses as handles for nodes.
console.log("second call of neoNode" + neoNode);
var alpha = neoNode.data; //this just doesn't work
console.log("alpha is: " +alpha); //returns undefined
var beta = JSON.stringify(alpha);
console.log("logging the node: ");
console.log(beta);// still undefined
res.render("results",{path: beta});
res.end('end');
}
function talkToNeo (reqnode, res) {
var params = {
};
var query = [
'MATCH (a {xml_id:"'+ reqnode +'"})',
'RETURN (a)'
].join('\n');
console.log(query);
db.query(query, params, function (err, results) {
if (err) throw err;
var neoNode = results.map(function (result){
return result['a']; //this returns a long string, looks like an array,
//but the values cannot be fetched out
});
console.log("this is the value of neoNode");
console.log(neoNode);
resultants(neoNode, res);
});
};
exports.queryanode = function (req, res) {
console.log('queryanode called');
if (req.method =='POST'){
var reqnode = req.body.node; //this works as it should, the neo4j query passes in
talkToNeo(reqnode, res) //the right value.
}
}
EDIT
Hey, I just wanted to answer my own question for anybody googling node, neo4j, data, or "How do I get neo4j properties?"
The gigantic object from neo4j, that when you stringified it you got all the "http://localhost:7474/db/data/node/7056/whatever" urls everywhere, that's JSON. You can query it with its own notation. You can set a variable to the value of a property like this:
var alpha = unfilteredResult[0]["nodes(p)"][i]._data.data;
Dealing with this JSON can be difficult. If you're anything like me, the object is way more complex than any internet example can prepare you for. You can see the structure by putting it through a JSON Viewer, but the important thing is that sometimes there's an extra, unnamed top layer to the object. That's why we call the zeroth layer with square bracket notation as such: unfilteredResult[0] The rest of the line mixes square and dot notation but it works. This is the final code for a function that calculates the shortest path between two nodes and loops through it. The final variables are passed into a Jade view.
function talkToNeo (nodeone, nodetwo, res) {
var params = {
};
var query = [
'MATCH (a {xml_id:"'+ nodeone +'"}),(b {xml_id:"' + nodetwo + '"}),',
'p = shortestPath((a)-[*..15]-(b))',
'RETURN nodes(p), p'
].join('\n');
console.log("logging the query" +query);
db.query(query, params, function (err, results) {
if (err) throw err;
var unfilteredResult = results;
var neoPath = "Here are all the nodes that make up this path: ";
for( i=0; i<unfilteredResult[0]["nodes(p)"].length; i++) {
neoPath += JSON.stringify(unfilteredResult[0]['nodes(p)'][i]._data.data);
}
var pathLength = unfilteredResult[0].p._length;
console.log("final result" + (neoPath));
res.render("results",{path: neoPath, pathLength: pathLength});
res.end('end');
});
};
I would recommend that you look at the sample application, which we updated for Neo4j 2.0
Which uses Cypher to load the data and Node-labels to model the Javascript types.
You can find it here: https://github.com/neo4j-contrib/node-neo4j-template
Please ask more questions after looking at this.