NodeJS websocket access second layer JSON Data - json

const WebSocket = require('ws');
const ws = new WebSocket('wss://www.bitmex.com/realtime?subscribe=instrument:XBTUSD');
ws.on('message', function incoming(a) {
p=JSON.parse(a)
console.log(Object.keys(p));
console.log(p.data);
});
code can be tried here - npm.runkit.com/ws
I am trying to access the subparameters of the JSON object like bidprice and ask price. However unable to go beyond the data level. Have tried using data[0].bidprice,data.bidprice but nothing works.
Not sure if p.data is returning a str instead of a JSON.
Sample data is as follows
{ table: 'instrument',
action: 'update',
data:
[ { symbol: 'XBTUSD',
lastPrice: 6686,
lastTickDirection: 'MinusTick',
lastChangePcnt: 0.0053,
timestamp: '2018-09-23T15:04:18.946Z' } ] }
if output is stored as var a, a.data works but a.data.symbol or a.data[0].symbol doesnt work

Related

Knex sometime return an empty string

I'm using knex with MYSQL. I have a function that I called to show the data to the user, Also I'm using a view table which has 5 right join on it and I think it will take some time to return values from the table plus I added the WHERE condition on my knex and it looks like this :
var showClass = (teacherId , ClassId){
return new Promise((resolve , reject)=>{
knex.select().from('v_cardex_details').where({teacherId }).andWhere({id : ClassId}).then(classes =>{
resolve(classes)
}).catch(err=>{
console.error(`Show Teacher class Error: ${err}`)
reject (err)
})
})
}
and I call this general function to response some request something like this
exports.EditClass = (req,res)=>{
knex('Table').update({//Some update stuff here}).then(()=>{
showClass(req.user.id, req.params.id).then(data=>{
return res.status(200).json({data , message:''})
})
}).catch()
}
With the same input, this function after updating returns value and some times it returns an empty string, especially when it's on the hosting server most of the time it returns nothing but { message : '' }
Try to create simplified code by removing all the unnecessary wrappers and you might find where your problem is. AFAIK there is no way that that your {data , message:''} would create an object containing just {message: ''} without any additional attributes.
> var data = []
undefined
> {data, foo:1}
{ data: [], foo: 1 }
> data = undefined
undefined
> {data, foo:1}
{ data: undefined, foo: 1 }
> {data1, foo:1}
ReferenceError: data1 is not defined
The problem you are experiencing does not exist in from the code you have shared (though there are syntax errors and other problems).
EDIT:
res.json() uses JSON.stringify() to convert js object to JSON strings. So if value of data in your code is undefined instead of and array, that could explain the behavior you are experiencing:
λ node
> JSON.stringify({ test: undefined })
'{}'
As you can see JSON.stringify() omits the attributes with value undefined from the output JSON string.

Appcelerator - Converting circular structure to JSON

I have a problem with converting a JSON in string. On iOS all works perfect but on Android I have this error:
[ERROR] : TiExceptionHandler: (main) [2,20592] - Message: Uncaught TypeError: Converting circular structure to JSON
This is my code:
var args = $.args
var data = args.data;
var oferta = data.oferta;
var params = data.params;
var parent = args.parent;
//INSERT
var producto = Alloy.createModel('Producto', {
oferta_id: parseInt(oferta.id),
data: JSON.stringify(args) //ERROR
});
The args passed to the controller are like this:
var args = {
data:
{
oferta: {id: 5},
params:{id_opcion_precio: 3445}
},
parent: {}
}
What's wrong?? Why on iOS works fine???
Not sure why you want to stringify args. Try to use JSON.stringify(args.data) when you create the model.
I guess you would have the same problem just stringify'ing args in a log statement like: console.log(JSON.stringify(args))?
I have run into similar problems when trying to write the entire event (e.g. from ti.map) to the console. Something makes it break - I assume there is added some attributes to the data that you don't see.
Finally I solved my problem doing this:
JSON.stringify({data: data, parent: parent});
This works I don't know why, but works

How can I update an existing JSON object's parameters in Grails?

I'm making a todo list. When first entering the item and adding it to the list, the server works great. It takes the parameters that the user selects and passes them into a list on the server that can be viewed by rendering Item.list(), that looks like so:
[{"class":"server.Item","id":1,"assignedTo":"User 1","comments":null,"completed":false,"creator":"User 1","name":"Task 1","priority":"1","type":"Personal"},
{"class":"server.Item","id":2,"assignedTo":"User 2","comments":null,"completed":false,"creator":"User 2","name":"Er","priority":"3","type":"Work"},
{"class":"server.Item","id":3,"assignedTo":"User 1","comments":null,"completed":false,"creator":"User 2","name":"Ga","priority":"1","type":"Work"}]
Now, the user then has the option to edit the task later. On the client side this works fine, but then I need the user to be able to save the new, updated task.
This is my current update function:
def updateList() {
def newItem = Item.findById(request.JSON.id)
newItem.assignedTo = request.JSON.assignedTo
newItem.comments = request.JSON.comments
newItem.completed = request.JSON.completed
newItem.creator = request.JSON.creator
newItem.name = request.JSON.name
newItem.priority = request.JSON.priority
newItem.type = request.JSON.type
newItem.save(flush: true)
render newItem as JSON
}
This doesn't work, however. I get a null pointer exception that says "Cannot set property "assignedTo" on null object. I'm assuming that the findById request is not getting anything for the JSON object, and thus there is no object to assign values to, however I don't know what the problem is considering the items are in fact being put into the Item.list().
This is called with the following JS function on the client side:
$scope.updateList = function() {
angular.forEach($scope.items, function (item) {
// serverList.save({command: 'updateList'}, item);
$http.post('http://localhost:8080/server/todoList/updateList', item)
.success(function(response) {})
.error(function(response) {alert("Failed to update");});
});
};
This might depend on your Grails version, but you should be able to do this:
def update(Item item) {
if (!item) {
// return a 404
} else {
// you should really use a service and not save
// in the controller
itemService.update(item)
respond item
}
}
Grails is smart enough look that item up since there is an ID in the JSON params, and populate the object correctly.
Sort of a work around for anyone else that may need to do this in a basic manner, what I've done that works is clear the list when "Update List" is clicked, then read back in the values that are currently in the client side list.
Grails:
def clearList() {
Item.executeUpdate('delete from Item')
render Item.list()
}
def updateList() {
def newItem = new Item(request.JSON)
newItem.save(flush:true)
render newItem as JSON
}
Javascript:
$scope.updateList = function() { // Update list on the server
serverList.get({command: 'clearList'});
angular.forEach($scope.items, function (item) {
serverList.save({command: 'updateList'}, item);
});
};

$resource : $save does not work

I have a json file called data.json containing some data:
[
{
"name" : "toto"
}
]
And the script I wrote to manage it :
var Data = $resource("data.json", {},
{
query: {method:'GET',isArray:true}
});
var data = Data.query(function()
{
var d = data[0];
d.name = "Titi";
d.$save();
});
Everything work before I call $save() on my object. I have this error:
[11:30:24.962] "Error: [$resource:badcfg] Error in resource configuration.
Expected response to contain an object but got an array
I don't really know the problem. I have already read many examples and documentations but this does not seem clearer to me.
Just guessing to help quickly here... You may have several issues, var d = data[0]. data should be from an argument/parameter of the function not the var data which is null until the return result from Data.query changes it. $save should also likely be on the $resource object, not the object in the array. Not an angular person, but guessing that might be the case.

Retrieve the data sent as JSON from JavaScript, inside a servlet

I have a query on retrieving data sent as JSON from a JavaScript, inside a Java servlet.
Following is what I am doing...
This is the part of the code inside JavaScript making a request to a servlet
type : "POST",
url: 'getInitialData',
datatype: 'json',
data : ({items :[{ name: "John", time: "2pm" },{name: "Sam", time: "1pm" }]}),
success: function(data) {
try{
////Code to be handeled where response is recieved
}catch(e){
alert(e);
}
}
On making this request I try to retrieve the parameters sent from JavaScript in a Servlet, but while doing so I was firstly confused on how to retrieve the dat from the request
I used the following in my servlet:
NOTE : the content Type in my Servlet is set to : apllication/json
response.setContentType("application/json");
request.getParameterMap();
the above showed me the data as below, but I was not able figure out how to work and get the actual data
{items[1][name]=[Ljava.lang.String;#1930089, items[0][time]=[Ljava.lang.String;#860ba, items[1][time]=[Ljava.lang.String;#664ca, items[0][name]=[Ljava.lang.String;#1c334de}
while the following code gave me Exception of null which was expected.
request.getParametervalues("items");
Among the others i tried where request.getParameter(); request.getParameterNames(); but in vain...
Am I in a wrong direction? Please guide me!
Please let me know how to retieve these value.
Thank You for reading this long post...
Sangeet
The request parameter map is a Map<String, String[]> where the map key is the parameter name and map value are the parameter values --HTTP allows more than one value on the same name.
Given the printout of your map, the following should work:
String item0Name = request.getParameter("items[0][name]");
String item0Time = request.getParameter("items[0][time]");
String item1Name = request.getParameter("items[1][name]");
String item1Time = request.getParameter("items[1][time]");
If you want a bit more dynamics, use the following:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String itemName = request.getParameter("items[" + i + "][name]");
String itemTime = request.getParameter("items[" + i + "][time]");
if (itemName == null) {
break;
}
// Collect name and time in some bean and add to list yourself.
}
Note that setting the response content type is irrelevant when it comes to gathering the request parameters.