problems parsing json response from Neo4j REST API query - json

After inserting a node containing 2 properties into a Neo4j database, how do I extract the properties ("name" and "phone") from a REST API query response? My script for querying the database is:
<script>
function query_database()
{
var restServerURL = "http://localhost:7474/db/data"; //local copy on windows machine
$.ajax({
type:"POST",
url: restServerURL + "/cypher",
accepts: "application/json",
dataType:"json",
data:{
"query" : "start n = node(*) return n",
"params" : {}
},
success: function(data, xhr, textStatus){
//alert("query success!");
//process query results here
alert(JSON.stringify(data, null, 4));
},
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}//end of query database
The "alert(JSON.stringify(data, null, 4));" displays the following:
{
"columns": [
"n"
],
"data": [
[
{
"paged_traverse": "http://localhost:7474/db/data/node/3761/paged/traverse/{returnType}{?pageSize,leaseTime}",
"outgoing_relationships": "http://localhost:7474/db/data/node/3761/relationships/out",
"data": {
"phone": "123.456.7890",
"name": "jeff "
},
"traverse": "http://localhost:7474/db/data/node/3761/traverse/{returnType}",
"all_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/all/{-list|&|types}",
"all_relationships": "http://localhost:7474/db/data/node/3761/relationships/all",
"property": "http://localhost:7474/db/data/node/3761/properties/{key}",
"self": "http://localhost:7474/db/data/node/3761",
"properties": "http://localhost:7474/db/data/node/3761/properties",
"outgoing_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/out/{-list|&|types}",
"incoming_relationships": "http://localhost:7474/db/data/node/3761/relationships/in",
"incoming_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/in/{-list|&|types}",
"extensions": {},
"create_relationship": "http://localhost:7474/db/data/node/3761/relationships"
}
]
]
}
Much thanks,
Jeff

In your example, you'd get the name and phone from the response data object like this:
var name = data.data[0][0].data.name;
var phone = data.data[0][0].data.phone;
alert("Name is " + name + "\nPhone is " + phone);
JSFiddle here.

Related

Replacing Slashes in JSON URL Data

I want to replace "\\" to "/" in productImage path, my code as below I used replace method but didn't work, waiting for your help thank you
const response = {
count: docs.length,
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
productImage: doc.productImage,
_id: doc._id,
request: {
type: "GET",
url: url + "/products/" + doc._id
}
};
})
};
My JSON Output
{
"name": " Sample Product",
"price": 45,
"productImage": "uploads\\2018-05-02T09-12-59.937Zahmet.jpg",
"_id": "5ae9811be170eb0a78500088",
"request": {
"type": "GET",
"url": "http://localhost:3000/products/5ae9811be170eb0a78500088"
}
},
You can split that value by \\, you'll get an array, join that array with /
var obj = {
"name": " Sample Product",
"price": 45,
"productImage": "uploads\\2018-05-02T09-12-59.937Zahmet.jpg",
"_id": "5ae9811be170eb0a78500088",
"request": {
"type": "GET",
"url": "http://localhost:3000/products/5ae9811be170eb0a78500088"
}
}
obj.productImage = obj.productImage.split("\\").join("/");
console.log(obj)

How to Retrieve (not create) Tasks from Asana using Apps Script & Personal Access Token

I am attempting to retrieve, but not create, tasks from Asana using Google Apps Script.
Using the Asana API Explore, I have constructed a URL that returns the data I desire: https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=987654321987654&completed_since=2018-02-22&limit=100&workspace=456789123456
This URL returns the desired data, in the following format:
{
"data": [
{
"id": 147258369147258,
"assignee_status": "inbox",
"name": "An example task name"
},
{
"id": 963852741963852,
"assignee_status": "upcoming",
"name": "And second example task name."
},
//etc...
]
}
With that URL as a model, I have created a Personal Access Token and executed the following function within Apps Script:
function getTasks5() {
// Asana Personal Token
var bearerToken = "Bearer " + "asdf123456789asdf456789456asdf";
//Request
var request = {
data: {
opt_fields: ["name", "assignee_status"],
assignee: "987654321987654",
completed_since: "2018-02-22",
limit: "100",
workspace: "456789123456"
}
};
// Request options
var options = {
method: "GET",
headers: {
"Authorization": bearerToken
},
contentType: "application/json",
payload: JSON.stringify(request)
};
var url = "https://app.asana.com/api/1.0/tasks";
var result = UrlFetchApp.fetch(url, options);
var reqReturn = result.getContentText();
Logger.log(reqReturn);
}
Instead of returning the desired data as the aforementioned URL does, the function creates an unnamed task in Asana, which is undesirable. It also returns this response containing undesired data:
{
"data": {
"id": 123456789123456,
"created_at": "2018-02-22T20:59:49.642Z",
"modified_at": "2018-02-22T20:59:49.642Z",
"name": "",
"notes": "",
"assignee": {
"id": 987654321987654,
"name": "My Name Here"
},
"completed": false,
"assignee_status": "inbox",
"completed_at": null,
"due_on": null,
"due_at": null,
"projects": [],
"memberships": [],
"tags": [],
"workspace": {
"id": 456789123456,
"name": "Group Name Here"
},
"num_hearts": 0,
"num_likes": 0,
"parent": null,
"hearted": false,
"hearts": [],
"followers": [
{
"id": 987654321987654,
"name": "My Name Here"
}
],
"liked": false,
"likes": []
}
}
Is it possible to simply GET a list of tasks in the manner exemplified by my first JSON example above without creating a task, and without resorting to using OAuth? If so, what changes to the Apps Script function need to be made?
Alright, the problem was with the approach I was taking. Rather than format the request with a payload (which infers a POST request), I needed to structure it more traditionally as a GET request, like so:
var requestUrl = "https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=123456789123&completed_since=2018-02-22&limit=100&workspace=987654321987";
var headers = {
"Authorization" : "Bearer " + AUTH_TOKEN
};
var reqParams = {
method : "GET",
headers : headers,
muteHttpExceptions: true
};
Then I was able to perform:
UrlFetchApp.fetch(requestUrl, reqParams);
And obtain the data I was after.

MongoDB, NodeJS: updating an embedded document with new members

Using: MongoDB and native nodeJS mongoDB driver.
I'm trying to parse all the data from fb graph api, send it to my API and then save it to my DB.
PUT handling in my server:
//Update user's data
app.put('/api/users/:fbuser_id/:category', function(req, res) {
var body = JSON.stringify(req.body);
var rep = /"data":/;
body = body.replace(rep, '"' + req.params.category + '"' + ':');
req.body = JSON.parse(body);
db.fbusers.update({
id: req.params.fbuser_id
}, {
$set: req.body
}, {
safe: true,
multi: false
},
function(e, result) {
if (e) return next(e)
res.send((result === 1) ? {
msg: 'success'
} : {
msg: 'error'
})
});
});
I'm sending 25 elements at a time, and this code just overrides instead of updating the document.
Data I'm sending to the API:
{
"data": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Basically my API changes "data" key from sent json to the category name, f.e.:
PUT to /api/users/000/likes will change the "data" key to "likes":
{
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Then this JSON is put to the db.
Hierarchy in mongodb:
{
"_id": ObjectID("556584c8e908f0042836edce"),
"id": "0000000000000",
"email": "XXXX#gmail.com",
"first_name": "XXXXXXXX",
"gender": "male",
"last_name": "XXXXXXXXXX",
"link": "https://www.facebook.com/app_scoped_user_id/0000000000000/",
"locale": "en_US",
"name": "XXXXXXXXXX XXXXXXXXXX",
"timezone": 3,
"updated_time": "2015-05-26T18:11:59+0000",
"verified": true,
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
....and so on
}
]
}
So the problem is that my api overrides the field (in this case "likes") with newly sent data, instead of appending it to already existing data document.
I am pretty sure that I should be using other parameter than "$put" in the update, however, I have no idea which one and how to pass parameters to it programatically.
Use $push with the $each modifier to append multiple values to the array field.
var newLikes = [
{/* new item here */},
{/* new item here */},
{/* new item here */},
];
db.fbusers.update(
{ _id: req.params.fbuser_id },
{ $push: { likes: { $each: newLikes } } }
);
See also the $addToSet operator, it adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

How to retrieve/display title, units, copyright along with JSON data in Highcharts

I have successfully implemented code for a JSONP request, retrieving data for multiple countries and displaying them as lines in a chart.
However, I would need to get the title, units, copyright etc. from the JSON as well, to be able to display that elements on the graph too.
Now, I wonder how this could be done.
The JSON response could look like this:
[
[
"series",
[
{
"data": [
[
2007,
2239300
],
[
2008,
2237490
],
[
2009,
2167070
],
[
2010,
2204450
]
],
"name": "France"
},
{
"data": [
[
2007,
2324234
],
[
2008,
3456352
],
[
2009,
1241422
],
[
2010,
4543231
]
],
"name": "Germany"
}
]
],
[
"title",
{
"text": "Title here"
}
],
[
"yAxis",
{
"text": "The units here"
}
]
]
My client's code would need to be changed then. For the moment it looks like this:
$.getJSON(url, {selectedCountries: "France,Germany,Switzerland", type: "jsonp"})
.done(function(data)
{
options.series = data;
var chart = new Highcharts.Chart(options);
})
.fail(function(jqxhr, textStatus, error)
{
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
})
And I guess it must turn into something like this:
options.series = data['series']['data'];
options.title = data['title'];
But that doesn't work. Could anyone give me a hint what I should do? Thanks a lot!
Ok, got it going finally. One has to pass the JSON as an object (and not an array, and neither as string (so, no quotes like ' or " around the object!). Works like a charm here on fiddle.
Here the code:
$(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline',
marginBottom: 50
},
series: [{}]
};
data = {
"title": {
"text": "Here goes the title"
},
"yAxis": {
"title": {
"text": "Here go the units"
}
},
"series": [{
"name": "France",
"data": [[2006,2189260],[2007,2239300],[2008,2237490],[2009,2167070],[2010,2204450]]
}]
};
options.series = data["series"];
options.title = data["title"];
options.yAxis = data["yAxis"];
var chart = new Highcharts.Chart(options);
});
Thanks a lot for Sebastian Bochan's great support!

Extract Json data on client side

I have following JSON data coming to client. I need to extract the data somehow so I can loop through it to get all name & count values.
{
"summarydata": {
"rows": [
{
"name": "Cisco0 Webinar US",
"count": "1"
},
{
"name": "Resource Nation CC",
"count": "1"
},
{
"name": "test",
"count": "10"
},
{
"name": "test",
"count": "2"
},
{
"name": "Vendor Seek",
"count": "1"
}
]
}
}
$.extend($.jgrid.defaults,
{ datatype: 'jsonstring' },
{ ajaxGridOptions: { contentType: "application/json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#BuyBackGrid")[0];
thegrid.addJSONData(data.data);
var summaryresult = $.parseJSON(data.summarydata.rows[0]);
alert(summaryresult );// this gives me null
alert(data.summarydata.rows[0].name); //this gives me first name element which is "Cisco0 Webinar US" in my case.
// alert($.parseJSON(data).summarydata.rows[0].name);
}
} //end of success
}//end of ajaxGridOptions
});
Leveraging jQuery...
The $.getJSON() function parses a local JSON file and returns it as an object.
$.getJSON("myJSON.js", function(json){
alert(json.summarydata.rows[0].name);
});
You could also just do this, using the JSON library for javascript (the object is also standard in most recent browsers).
alert(JSON.parse(myJSONString).summarydata.rows[0].name);