I'm a java-script newbee, that's why I struggle with the mapping of a simple json array, if it is a response from a server. I've tested it with static json, and it works as expected:
new gridjs.Grid({
columns: [{
id: 'dateTime',
name: 'Timestamp'
}, {
id: 'host',
name: 'Host'
}, {
id: 'ipv4',
name: 'IPv4'
}, {
id: 'ipv6',
name: 'IPv6'
}],
data: [
{"dateTime": "2021-12-02 03:11:30.501","host": "master.myhost.com","ipv4": "93.215.66.14", "ipv6": "2003:cc:2fff:9e4:2e91:abff:febf:d839"},
{"dateTime": "2021-12-02 03:44:29.494", "host": "test.myhost.com", "ipv4": "93.203.250.190", "ipv6": "n/a"},
]
}).render(document.getElementById("wrapper"));
But if the same json array is delivered by a server, I don't know how to define my data mapping. That's what I've tried:
new gridjs.Grid({
columns: [{
id: 'dateTime',
name: 'Timestamp'
}, {
id: 'host',
name: 'Host'
}, {
id: 'ipv4',
name: 'IPv4'
}, {
id: 'ipv6',
name: 'IPv6'
}],
server: {
url: "http://localhost:8080/info/zone-log",
then: data => data.map([data.dateTime, data.host, data.ipv4, data.ipv6])
}
}).render(document.getElementById("wrapper"));
I get the following error on the JS console: '[Grid.js] [ERROR]: TypeError: [...] is not a function'.
Can somebody explain me, how to do the data mapping correctly?
Edit
Server response:
curl -i http://localhost:8080/info/zone-log
HTTP/1.1 200 OK
Date: Tue, 01 Mar 2022 08:53:39 GMT
Content-Type: application/json
Transfer-Encoding: chunked
[{"dateTime":"2021-12-02 03:11:30.501","host":"master.myhost.com","ipv4":"93.215.66.14","ipv6":"2003:cc:2fff:9e4:2e91:abff:febf:d839"},{"dateTime":"2021-12-02 03:44:29.494","host":"ursa.myhost.com","ipv4":"93.203.250.190","ipv6":"n/a"}, ...}
java-script console log:
data
Array(191) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
[0…99]
0: Object { dateTime: "2021-12-02 03:11:30.501", host: "master.myhost.com", ipv4: "93.215.66.14", … }
1: Object { dateTime: "2021-12-02 03:44:29.494", host: "ursa.myhost.com", ipv4: "93.203.250.190", … }
[Grid.js] [ERROR]: TypeError: [...] is not a function log.ts:12:21
Looks like data that you are getting is not an array. Hence data.map() is giving type error. Can you please console log the data and see what's coming?
new gridjs.Grid({
columns: [{
id: 'dateTime',
name: 'Timestamp'
}, {
id: 'host',
name: 'Host'
}, {
id: 'ipv4',
name: 'IPv4'
}, {
id: 'ipv6',
name: 'IPv6'
}],
server: {
url: "http://localhost:8080/info/zone-log",
then: data => {
console.log("data", data);
return data.map([data.dateTime, data.host, data.ipv4, data.ipv6])
}
}
}).render(document.getElementById("wrapper"));
Most probably the required array is inside another object in data.
Related
I am trying to download stock data using Alpha Vantage API. I send a request and after some work on responded data I have an array like below:
[
{
id: "MSFT",
stockData: [
{ date: "1634601600", summary: [Object] },
{ date: "1634688000", summary: [Object] } ]
}
]
And [Object] is something like:
{
date: "1646956800",
summary: { open: 287.96, high: 289.51, low: 279.43, close: 280.07, volume: 27209330 }
}
But I don't know how can I save it into the MongoDB? I could save a simpler structure and I knew I must create a class with the same property names as the response JSON, then instantiate the class and assign the properties of the response value to the properties of the class instance then save it to the database.
But now I am a little confused and don't know how properly deal with this. Also what if I have an array with more nested values of different size like below:
[
{
id: "AAPL",
stockData: [
{ date: 1634601600, summary: [Object] },
{ date: 1634688000, summary: [Object] },
{ date: 1634774400, summary: [Object] },
{ date: 1634860800, summary: [Object] }
]
},
{
id: "MSFT",
stockData: [
{ date: 1634601600, summary: [Object] },
{ date: 1634688000, summary: [Object] }
]
}
]
i have a problem with fetch data from api exposed by spring.
I want to fetch data by:
componentDidMount() {
this.setState({isLoading: true});
fetch('http://localhost:8080/api/tasks/')
.then(response => { return response.json() })
.then(results => this.setState({
tasks: results,
isLoading: false
}));
The spring api which return data:
#CrossOrigin(origins = "http://localhost:3000")
#GetMapping
public List<Task> findTasksByUserId() {
return taskService.findTasksBelongToUser(idProvider.getCurrentUserId());
}
Returned JSON:
[
{
id: 1,
version: 0,
name: "Task1",
description: "description1",
priority: 1,
finished: true,
category: {
id: 1,
version: 0,
name: "Uncategorized",
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
}
},
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
},
position: 0
},
{
id: 2,
version: 0,
name: "Task2",
description: "description2",
priority: 4,
finished: true,
category: {
id: 1,
version: 0,
name: "Uncategorized",
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
}
},
user: {
id: 1,
version: 0,
login: "admin",
email: "admin#todo.pl",
enabled: true
},
position: 1
}]
And i got a error like this:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I dont know what is wrong but maybe format of json is not correct, because it's start with the sign '['.
I am a beginner in React so please about some hint and help.
regards
fetch() returns a promise which gets resolved into an HTTP response of course, not the actual JSON. To extract the JSON body content from the response, we use the json() method.
Try adding two headers Content-Type and Accept to be equal to application/json.
fetch('http://localhost:8080/api/tasks/', {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => { return response.json() })
.then(results => this.setState({
tasks: results,
isLoading: false
}));
I have an elasticsearch database that I access through a node.js client. I can parse the JSON from elasticsearch to print out the hitsArray which looks like below:
[ { _index: 'parties',
_type: 'suppliers',
_id: 'AV0uELknL82XeGsCOZ-i',
_score: 1,
_source: { name: 'Jabil', address: [Object], rating: 4.2 } },
{ _index: 'parties',
_type: 'suppliers',
_id: 'AV0t_yC3L82XeGsCOZ-f',
_score: 1,
_source: { name: 'Apple', address: [Object], rating: 4.9 } },
{ _index: 'parties',
_type: 'suppliers',
_id: 'AV0t_glkL82XeGsCOZ-d',
_score: 1,
_source: { name: 'Flextronics', address: [Object], rating: 4.5 } },
{ _index: 'parties',
_type: 'suppliers',
_id: 'AV0t_ox7L82XeGsCOZ-e',
_score: 1,
_source: { name: 'FlashMob', address: [Object], rating: 3.5 } } ]
Now, I want to parse the _source field and print out the name field
client.search(searchParams).then(function (resp) {
return Promise.all(resp.hits.hits)
}).then(function(hitsArray){
hitsArray.forEach(function(value){
JSONObject first = hitsArray.getJSONObject(value);
JSONObject source = first.getJSONObject("_source");
String name = source.getString("name");
console.log(name);
});
});
But I am getting error
JSONObject first = hitsArray.getJSONObject(value);
^^^^^
SyntaxError: Unexpected identifier
What am I missing? any suggestion?
JavaScript has no explicit type definitions like that. It looks like those 3 lines may be Java code and not JavaScript code.
As far as getting the actual JavaScript value goes, it appears to already be an object. Just access it with value._source (and value._source.name).
I want that my model fields will store in mysql as it is. My user model is like this:
module.exports = {
attributes: {
local: {
email: 'string',
password: 'string'
},
facebook: {
id: 'string',
token: 'string',
email: 'string',
name: 'string'
},
google: {
id: 'string',
token: 'string',
email: 'string',
name: 'string'
}
}
};
But this does not create any field in user model. What should I do for storing these fields in mysql ?
You'll need to save them as JSON objects. Sails will stringify your objects and save the result in your database. It will also take care of the parsing, so you don't have to worry about that. Still it doesn't allow specifying the inner attributes of the objects, but I don't think there's a solution for that.
module.exports = {
attributes: {
local: {
type: 'json'
},
facebook: {
type: 'json'
},
google: {
type: 'json'
}
}
};
In my Angular.js service I've created a custom request:
.factory('CalendarService', ['$resource',
function($resource) {
return {
Update: function(bookingObj) {
var BookingResource = $resource('http://localhost:1337/bookings/:id',{
id: '#id'
}, {
'update': {
method: 'PUT',
isArray: true
}
});
var bookingId = bookingObj.id;
return BookingResource.update({
id: bookingId
}, bookingObj).$promise;
}
On server side Sails.js seems properly configured with sails-mysql, I can make a get request with no errors, but when I call the update function I receive this error:
error: Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
: .findOne() requires a criteria. If you want the first record try .find().limit(1)
at module.exports.findOne (C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\adapter\dql.js:143:56)
at _runOperation (C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\query\finders\operations.js:
400:29)
at run (C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\query\finders\operations.js:69:8)
at bound.module.exports.findOne (C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\query\finders
\basic.js:66:16)
at bound [as findOne] (C:\prestigeweb\node_modules\sails\node_modules\lodash\dist\lodash.js:729:21)
at Deferred.exec (C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\query\deferred.js:501:16)
at updated (C:\prestigeweb\node_modules\sails\lib\hooks\blueprints\actions\update.js:83:9)
at bound (C:\prestigeweb\node_modules\sails\node_modules\lodash\dist\lodash.js:957:21)
at applyInOriginalCtx (C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\utils\normalize.js:416:80)
at wrappedCallback (C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\utils\normalize.js:315:18)
at _normalizeCallback.callback.success (C:\prestigeweb\node_modules\sails\node_modules\waterline\node_modules\switchb
ack\lib\normalize.js:33:31)
at _switch (C:\prestigeweb\node_modules\sails\node_modules\waterline\node_modules\switchback\lib\factory.js:48:28)
at C:\prestigeweb\node_modules\sails\node_modules\waterline\lib\waterline\query\dql\update.js:224:9
at done (C:\prestigeweb\node_modules\sails\node_modules\waterline\node_modules\async\lib\async.js:135:19)
at C:\prestigeweb\node_modules\sails\node_modules\waterline\node_modules\async\lib\async.js:32:16
at C:\prestigeweb\node_modules\sails\node_modules\waterline\node_modules\async\lib\async.js:157:25
Details: Error: .findOne() requires a criteria. If you want the first record try .find().limit(1)
This is the HTTP request from Postman:
PUT /bookings/6397 HTTP/1.1
Host: localhost:1337
Accept: application/json, text/plain, */*
Origin: http://localhost:8100
X-DevTools-Emulate-Network-Conditions-Client-Id: ABAC3370-A7E6-42AA-A5DA-BA0205880B9C
X-FirePHP-Version: 0.0.6
User-Agent: Mozilla/5.0 (iPad; CPU OS 4_3_5 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5
Content-Type: application/json;charset=UTF-8
DNT: 1
Referer: http://localhost:8100/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4,fr;q=0.2
Cache-Control: no-cache
Postman-Token: 0a627a0a-2f27-0e55-737f-5e838e1084e0
{"id":6397,bla bla bla}
this is how I configured Sails.js:
1) sails generate api bookings
2) npm-install sails-mysql
3) inserted in config/connections.js the following line
mysql: {
adapter: 'sails-mysql',
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'prestige'
},
4) added to config/cors.js:
allRoutes: true,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD'
origin: '*'
5) on config/model.js added
module.exports.models = {
connection: 'mysql',
migrate: 'safe'
};
The sails.js: model:
module.exports = {
tableName: 'prenotazioni',
adapter: 'mysql',
//migrate: 'safe',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
id: {
type: 'integer'
},
numero_prenotazione: {
type: 'string'
},
nome: {
type: 'string'
},
cognome: {
type: 'string'
},
civico: {
type: 'string'
},
indirizzo: {
type: 'string'
},
ditta: {
type: 'string'
},
cap: {
type: 'string'
},
citta: {
type: 'string'
},
nazione: {
type: 'string'
},
lingua: {
type: 'string'
},
telefono: {
type: 'string'
},
email: {
type: 'string'
},
agente: {
type: 'string'
},
numero_camere: {
type: 'integer'
},
numero_ospiti: {
type: 'integer'
},
costo_totale_camere: {
type: 'integer'
},
ospite_1: {
type: 'string'
},
ospite_2: {
type: 'string'
},
camera_1: {
type: 'string'
},
camera_2: {
type: 'string'
},
numero_persone_1: {
type: 'integer'
},
numero_persone_2: {
type: 'integer'
},
data_prenotazione: {
type: 'date'
},
data_arrivo_1: {
type: 'date'
},
data_arrivo_2: {
type: 'date'
},
data_partenza_1: {
type: 'date'
},
data_partenza_2: {
type: 'date'
},
quantita_1: {
type: 'integer'
},
quantita_2: {
type: 'integer'
},
totale_1: {
type: 'integer'
},
totale_2: {
type: 'integer'
},
prezzo_1: {
type: 'integer'
},
prezzo_2: {
type: 'integer'
},
status_1: {
type: 'integer'
},
status_2: {
type: 'integer'
},
duration: {
type: 'string'
}
}
};
In your model:
module.exports = {
...
autoPK: false,
attributes: {
id: {
type: 'integer',
autoIncrement: true,
primaryKey: true
},
...
}
}
Further reading: Waterline docs.