undefined JSON object / Array Javascript - arrays

JSON Data
myData = {"data":[{"pre":1,"post":2}]}
JSON.stringify(myData) shows that data is an array with one element, an object.
console.log("type of data: " + typeof(myData));
console.log("data: " + JSON.stringify(myData));
console.log("data.pre: " + data.pre);
Log result
type of data: object
data: {"data":[{"pre":1,"post":2}]}
data.pre: undefined
I manually adjusted and added a JSON.
It works with this JSON (without the object)
myData = {"pre":1,"post":2}
and
console.log("data.pre: " + data.pre);
Log result
data.pre: 1
How can i achieve this? I want to use it later as a variable.
pre = data.pre;
post = data.post;

If your data inside an array you need to specify the index of the object you want to access ex: data[0].pre
myData = {"data":[{"pre":1,"post":2}]}
console.log("type of data: " + typeof(myData));
console.log("type of data: " + typeof(myData.data));
console.log("data: " + JSON.stringify(myData.data));
console.log("data.pre: " + myData.data[0].pre);
console.log("data.post: " + myData.data[0].post);

Related

Spring boot - I want to write a POST endpoint to consume multipart/form-data WITHOUT any file uplload, I need to post json data as key-value pair pair

I want to do something like this -
#ApiOperation("Solve for tasks in JSON file")
#PostMapping(value = "/tasks/file",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Plan> solveTest(#RequestBody(value = "file") InputStream filrInputStream) {}
I tried adding jersey multipart dependency in my spring boot app and tried my api method signature as below, but when I try posting my json string I get input stream as empty-
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
#ApiImplicitParams({
#ApiImplicitParam(
name = "file",
dataType = "java.io.InputStream",
examples = #io.swagger.annotations.Example(
value = {
#ExampleProperty(value = "[\r\n"
+ " {\r\n"
+ " \"duration\": 0,\r\n"
+ " \"xxxxxxTG\": \"string\",\r\n"
+ " \"sequence\": 0,\r\n"
+ " \"xxxxxx\": \"string\",\r\n"
+ " \"taskId\": \"string\",\r\n"
+ " \"taskType\": \"string\",\r\n"
+ " \"xcoordinate\": 0,\r\n"
+ " \"ycoordinate\": 0\r\n"
+ " }\r\n"
+ "]", mediaType = "multipart/form-data")
}))
})
#PostMapping(value = "/tasks/file",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE}
)
public ResponseEntity<Plan> solveTest1(#FormDataParam("file") InputStream file, #FormDataParam("file") FormDataContentDisposition fileMetaData)

Possible to download JPA repository in Vaadin as CSV file?

Assume that we have defined a entity and it's connected to a database. Now we can access the database by using a repository.
#Autowired
private DataLoggRepository dataLoggRepository;
If I want to get all the rows from the database and download it. Then I can write this code:
List<DataLogg> dataLoggers = dataLoggRepository.findAll();
Now, how can I donwload the object dataLoggers as a CSV file in Vaadin in a proper way?
Here you can see how to create a link to download a file:
Anchor csvLink = new Anchor(new StreamResource("file.csv",
() -> {
String csvString = ...// create the csv
return new ByteArrayInputStream(csvString.getBytes());
}), "Download CSV");
csvLink.getElement().setAttribute("download", true);
To create the CSV you have various options like OpenCSV or directly create the CSV from the SQL query.
Here is a working example
// Download all data
Anchor download = new Anchor(); // Add this to the layout
loggerId.addValueChangeListener(e-> {
String fileName = String.valueOf(loggerId.getValue()) + ".csv";
List<DataLogg> selectedLogger = dataLoggRepository.findByLoggerId(loggerId.getValue());
download.setHref(getStreamResource(fileName, selectedLogger));
});
download.getElement().setAttribute("download",true);
download.add(new Button("Download", new Icon(VaadinIcon.DOWNLOAD_ALT)));
Function
public StreamResource getStreamResource(String filename, List<DataLogg> selectedLogger) {
// Create a large CSV file in a form of StringBuilder and then convert it all to bytes
StringWriter stringWriter = new StringWriter();
stringWriter.write("id, dateTime, DO0, DO1, DO2, DO3, AI0, AI1, AI2, AI3, loggerId, samplingTime\n");
for (int i = 0; i < selectedLogger.size(); ++ i) {
DataLogg dataLogg = selectedLogger.get(i);
String row = dataLogg.getId() + "," +
dataLogg.getDateTime() + "," +
dataLogg.getDO0() + "," +
dataLogg.getDO1() + "," +
dataLogg.getDO2() + "," +
dataLogg.getDO3() + "," +
dataLogg.getAI0() + "," +
dataLogg.getAI1() + "," +
dataLogg.getAI2() + "," +
dataLogg.getAI3() + "," +
dataLogg.getLoggerId() + "," +
dataLogg.getSamplingTime() + "\n";
stringWriter.write(row);
}
// Try to download
try {
byte[] buffer = stringWriter.toString().getBytes("UTF-8");
return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
} catch (UnsupportedEncodingException e) {
byte[] buffer = new byte[] {0};
return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
}
}

PostgresSql + Nodejs (ClaudiaJS) : How to cast array of string to array of timestamp

I am writing API which insert into a table with multiple rows, I am using UNNEST to make it work.
What I have done:
in js file:
api.post(PREFIX + '/class/insert', function (request) {
var db = pgp(dbconnect);
//Params
var data = request.body; //should be an array
var classes = [];
var starts = [];
var ends = [];
for (var i = 0; i < data.length; i++) {
classes.push(data[i].class_id);
starts.push(data[i].timestamp_start);
ends.push(data[i].timestamp_end);
}
const PQ = require('pg-promise').ParameterizedQuery;
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"
const final_sql = new PQ(sql);
return db.any(final_sql)
.then(function (data) {
pgp.end();
return 'successful';
})
.catch(function (error) {
console.log("Error: " + error);
pgp.end();
});
}
Request body
[{
"class_id":"1",
"timestamp_start":"2017-11-14 14:01:23.634437+00",
"timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
"class_id":"2",
"timestamp_start":"2017-11-14 15:01:23.634437+00",
"timestamp_end": "2017-11-14 16:20:23.634437+00"
}]
When I run api in postman, I get the error is:
column "timestamp_start" is of type timestamp with time zone but
expression is of type text
Issue is obviously from ARRAY of string that I used in sql, my question is how to create ARRAY of timestamp for UNNEST, or any suggestion are appreciated.
Thanks
Never initialize the database inside the handler, see: Where should I initialize pg-promise
Never call pgp-end() inside HTTP handlers, it destroys all connection pools.
Use static ColumnSet type to generate multi-insert queries.
Do not return from db.any, there is no point in that context
You must provide an HTTP response within an HTTP handler
You are providing a confusing semantics for column class_id. Why is it called like that and yet being converted into a timestamp?
Never concatenate objects with strings directly.
Never concatenate SQL strings manually, it will break formatting and open your code to SQL injection.
Use Database methods according to the expected result, i.e. none in your case, and not any. See: https://github.com/vitaly-t/pg-promise#methods
Initialize everything needed only once:
const db = pgp(/*connection*/);
const cs = new pgp.helpers.ColumnSet([
'class_id',
{
name: 'timestamp_start',
cast: 'timestamp'
},
{
name: 'timestamp_end',
cast: 'timestamp'
}
], {table: {table: 'class', schema: 'sa1'}});
Implement the handler:
api.post(PREFIX + '/class/insert', request => {
const sql = pgp.helpers.insert(request.body, cs);
db.none(sql)
.then(data => {
// provide an HTTP response here
})
.catch(error => {
console.log('Error:', error);
// provide an HTTP response here
});
}
Many thanks to #JustMe,
It worked after casting array
var sql =
"INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
"VALUES( "+
"UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
"UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "::timestamp[]), " +
"UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + "::timestamp[])"

Access json array from navigator.camera.getPicture Cordova response

I am getting a response after I run a function that calls a cordova navigator.camera.getPicture() function. All works well and the response is below, however I can not access individual value-pairs
({"tagone" : "optimal", "datex" : "Thursday"})
I try this: r.response['tagone'] and just returns empty.
$scope.win = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
$("#camLoader").hide();
$("#resultDiv").show();
$("#finalResult").append(r.response['tagone']);
//alert(r.response);
};

Appcelerator Cloud Services Posts Object Query using AngularJS

All,
I am using Appcelerator Cloud Services as my backend for an AngularJS/Ionic Framework/PhoneGap mobile app I am working on. I am trying to query the ACS Posts object by user_id and tags_array.
My code is at the following gist :
https://gist.github.com/bp4151/d6828f8d7af983316f99
I am formatting the query string as follows:
getByFriends: function(user_ids, tag) {
var query = "where={$and[{'user_id':$in['" + user_ids + "']},{'tags_array':$in['" + tag + "']}]}";
return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' + globals.ACSKey + '&query=' + query + '&_session_id = ' + globals.session_id);
},
I modified the code to the following, but I am still having no luck
getByFriends: function(user_ids, tag) {
//return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' + globals.ACSKey + '&query=' + query + '&_session_id = ' + globals.session_id);
return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' + globals.ACSKey + '&_session_id = ' + globals.session_id, {
params: {
query: "where={$and[{'user_id':$in['" + user_ids + "']},{'tags_array':$in['" + tag + "']}]}"
}
});
},
I expect only one post record to be returned with the id I am passing in (532f233f1316e90b760eca00) but I am getting all posts back no matter what I try. If anyone can point my in the right direction, I would really appreciate it.
Thanks,
Bruce
I figured it out. The issues are
the params block is not set up properly,
I need to decode the string that is being sent.
I was confused by the documentation that stated query: where=... The correct way to do this with Angular is as I coded it below using "where":...
get: function(user_id, tag) {
console.log('PostService.get');
return $http.get('https://api.cloud.appcelerator.com/v1/posts/query.json?key=' +
globals.ACSKey,
{
params: {
"where": decodeURIComponent('{"user_id": {"$in":["' + user_id + '"]},
"tags_array":"' + tag + '"}')
}
});
},

Resources