I have a simple array of categories coming from server. Each category is a dictionary.
var json = JSON(json!)
println(json)
for (index: String, subJson: JSON) in json {
println(subJson)
The subjs. printout is:
{
"thumbnailImage" : null,
"isNew" : true,
"id" : 30,
"name" : "Abilities",
"mainImage" : null
}
So shouldn't :
if let extId = subJson["id"].string{
NSLog(subJson["id"].string!)
}
Run and log "30"? It never passes the conditional.
What am I obviously doing wrong?
It was a number, I was casting it to string, it worked with:
subjs.["id].number
Related
I have a User (id, username) entity which has many-to-many relationship with Roles (id, name) entity. I am trying to show the User data in a ajax Datatable. Now, if a User has six roles, it shows six [object Object] for all six roles. I dont know how to correctly show the role name instead of object Object.
This is what I have:
.DataTable(
{
"pagingType" : "full_numbers",
"sAjaxSource" : "/api/AppUser/all",
"sAjaxDataProp" : "",
"aoColumns" : [
{
"data" : "id"
},
{
"data" : "username"
},
{
"data" : "userenabled"
},
{
"data" : "useremail"
},
{
"data" : "userfirstname"
},
{
"data" : "userlastname"
},
{
"data" : "useraddress"
},
{
"data" : "roles"
}
This is how it looks like in Data Table:
Here is my REST Controller piece:
#RestController
#RequestMapping("/api/AppUser")
public class AppUserRestAPIs {
#GetMapping(value = "/all", produces = "application/json")
public List<AppUser> getResource() {
return appUserJPARepository.findAll();
}
}
I know it must be trivial but feeling lost and could not find a single example on how to represent relationship data in view (html) using REST api. Searched almost everywhere. What I am missing here? Will appreciate any pointers here.
Answering my own question:
Found it ! Here - https://editor.datatables.net/examples/advanced/joinArray.html
So instead of:
{
"data" : "roles"
}
I have to use:
{
"data" : "roles",
render : "[, ].name"
}
All worked perfectly but now I am clueless what if I don't use Datatable. Not sure if I have to put another question for it.
Use function to flat roles list:
Instead of
{
"data" : "roles"
}
Try this :
{
"data": null,
"render": function(data, type, row, meta) {
var flatrole = '';
//loop through all the roles to build output string
for (var role in data.roles) {
flatrole = flatrole + role.name + " ";
}
return flatrole;
}
}
I have a Kotlin function which creates a model with a hashmap as shown below
#GetMapping("/")
fun index(model: Model): Mono<String> {
model.addAttribute("images", imageService.findAllImages()?.flatMap { image ->
Mono.just(image)
.zipWith(repository.findByImageId(image?.id!!).collectList())
.map({ imageAndComments: Tuple2<Image?, MutableList<learningspringboot.images.Comment>> ->
hashMapOf<String, Any?>(
"id" to imageAndComments.t1?.id,
"name" to imageAndComments.t1?.name,
"comments" to imageAndComments.t2)
}).log("findAllImages")
})
model.addAttribute("extra", "DevTools can also detech code changes.")
return Mono.just("index")
}
Image.kt
package learningspringboot.images
import org.springframework.data.annotation.Id
data class Image(#Id var id: String? = null, var name: String? = null)
Comment.kt
package learningspringboot.images
import org.springframework.data.annotation.Id
data class Comment #JvmOverloads constructor(#Id private var id: String? = null, private var imageId: String? = null, private var comment: String? = null) {
}
In my Thymeleaf template I have
<ul><li th:each = "Comment :${image.comments}" th:text = "${image.comments}"></li></ul>
Which gives me this lines like
[Comment(id=5a623d5d2298352bc4929866, imageId=0d46b575-b6ce-48e2-988a-ebe62ebc2ceb, comment=test), Comment(id=5a623d8b2298352bc4929867, imageId=0d46b575-b6ce-48e2-988a-ebe62ebc2ceb, comment=test23)]
Which shows the comment record as is with the MongoDB keys/ids and everything else. This is not what I want.
I also have this in my Thymeleaf template
<ul><li th:each = "Comment :${image.comments}" th:text = "${comment == null ? 'empty' : comment.Comment}"></li></ul>
Which shows the word empty for each comment record.
The comment record in the database looks like
{ "_id" : ObjectId("5a623d5d2298352bc4929866"), "imageId" : "0d46b575-b6ce-48e2-988a-ebe62ebc2ceb", "comment" : "test", "_class" : "learningspringboot.comments.Comment" }
The image records in the database looks like
{ "_id" : ObjectId("5a623d5d2298352bc4929866"), "imageId" : "0d46b575-b6ce-48e2-988a-ebe62ebc2ceb", "comment" : "test", "_class" : "learningspringboot.comments.Comment" }
{ "_id" : ObjectId("5a623d8b2298352bc4929867"), "imageId" : "0d46b575-b6ce-48e2-988a-ebe62ebc2ceb", "comment" : "test23", "_class" : "learningspringboot.comments.Comment" }
How can I unwrap the comments records so that I only see the "comment" values and not the "_id" or "imageId" values?
The problem is that I have a hashmap<string>,arraylist<image>.
So I simply need to loop through all the image elements in the array list using thymeleaf. I'm pretty sure that this has been done before, I'll just need to find a good example and do some reading.
I was able to use the following code
<th:block th:each="Comment : ${image.comments}">
<ul th:each="comment : ${Comment}">
<li th:text="${comment.comment}"></li>
</ul>
</th:block>
And now I can move on.
I need to select users that have a "3" in their json array.
{
"People":[
{
"id" : "123",
"firstName" : "Bill",
"lastName" : "Gates",
"roleIds" : {
"int" : ["3", "9", "1"]
}
},
{
"id" : "456",
"firstName" : "Steve",
"lastName" : "Jobs",
"roleIds" : {
"int" : ["3", "1"]
}
},
{
"id" : "789",
"firstName" : "Elon",
"lastName" : "Musk",
"roleIds" : {
"int" : ["3", "7"]
}
},
{
"id" : "012",
"firstName" : "Agatha",
"lastName" : "Christie",
"roleIds" : {
"int" : "2"
}
}
]}
In the end, my results should be Elon Musk & Steve Jobs. This is the code that I used (& other variations):
var roleIds = pplFeed["People"]["roleIds"].Children()["int"].Values<string>();
var resAnAssocInfo = pplFeed["People"]
.Where(p => p["roleIds"].Children()["int"].Values<string>().Contains("3"))
.Select(p => new
{
id = p["id"],
FName = p["firstName"],
LName = p["lastName"]
}).ToList();
I'm getting the following error:
"Accessed JArray values with invalid key value: "roleIds". Int32 array index expected"
I changed .Values<string>() to .Values<int>() and still no luck.
What am I doing wrong?
You are pretty close. Change your Where clause from this:
.Where(p => p["roleIds"].Children()["int"].Values<string>().Contains("3"))
to this:
.Where(p => p["roleIds"]["int"].Children().Contains("3"))
and you will get you the result you want (although there are actually three users in your sample data with a role id of "3", not two).
However, there's another issue that you might hit for which this code still won't work. You'll notice that for Agatha Christie, the value of int is not an array like the others, it is a simple string. If the value will sometimes be an array and sometimes not, then you need a where clause that can handle both. Something like this should work:
.Where(p => p["roleIds"]["int"].Children().Contains(roleId) ||
p["roleIds"]["int"].ToString() == roleId)
...where roleId is a string containing the id you are looking for.
Fiddle: https://dotnetfiddle.net/Zr1b6R
The problem is that not all objects follow the same interface. The last item in that list has a single string value in the roleIds.int property while all others has an array. You need to normalize that property and then do the check. It'll be easiest if they were all arrays.
You should be able to do this:
var roleId = "3";
var query =
from p in pplFeed["People"]
let roleIds = p.SelectToken("roleIds.int")
let normalized = roleIds.Type == JTokenType.Array ? roleIds : new JArray(roleIds)
where normalized.Values().Contains(roleId)
select new
{
id = p["id"],
FName = p["firstName"],
LName = p["lastName"],
};
I've been trying, unsuccessfully, to get a yui3 datatable to correctly populate via a json call. I am flummoxed and hope someone can show me the error of my ways. No matter what I have tried I just get "No data to display".
When I run wireshark during the page load I am seeing the json data returned from the ajax call. So I think I have the data source bound to the data table correctly. Note that the data records I am interested in are nested with metadata and it appears my DataSourceJSONSchema definition is correct.
Here is the http response from the ajax call.
YUI.Env.DataSource.callbacks.yui_3_6_0_1_1346868215546_114({
"recordsReturned":4,"startIndex":0,"dir":"asc","pageSize":10,
"records":[
{"id":"48ee0540-ebd7-11e1-33e-c33ce39c9e", "email":"jim#example.com","name":"James"},
{"id":"1447ea60-eca2-11e1-33e-f6c33ce39c9e", "email":"john#example.com","name":"John"},
{"id":"48ff6a60-ebd7-11e1-a33e-f6c33ce39c9e", "email":"ryan#example.com","name":"Ryan"},
{"id":"1a298060-f774-11e1-ad38-f6c33ce39c9e", "email":"vincent#example.com","name":"Vince"}]})
Here is the html page.
<script type="text/javascript">
YUI({
lang : "en-US"
})
.use("datatable","datatype","datasource",function(Y) {
var ajaxData;
function ajaxSuccess(e) {
ajaxData = e.data;
}
}
function ajaxFailure(e) {
Y.log("failure");
}
var myDataSource = new Y.DataSource.Get({
source : "/actions/User.action?getAjaxUserList=&"
});
myDataSource.plug(Y.Plugin.DataSourceJSONSchema,{
schema : {
metaFields : {
recordsReturned : "recordsReturned",
startIndex : "startIndex",
dir : "dir",
pageSize : "pageSize"
},
resultsListLocator : "records",
resultFields : [ {
key : 'id'}, {
key : 'email'},{
key : 'name' }}});
var table = new Y.DataTable({
columns : [ {
key : "id",
label : "ID"
}, {
key : "name",
label : "Name"}, {
key : "email",
label : "Email"} ],
caption : "My first DataTable!",
summary : "Example DataTable showing basic instantiation configuration"
});
table.plug(Y.Plugin.DataTableDataSource, {datasource : myDataSource});
table.render('#dynamicdata');
table.datasource.load({request : encodeURIComponent('fred=steve')});
});
</script>
<div id="dynamicdata"></div>
I noticed several syntax error on the code you give here :
The function(Y) callback is closed too soon for example.
I think your error is due to the fact that you set in the schema of your Datasource the property "resultsListLocator" instead of "resultListLocator".
I'm trying to get MongoDB to upsert multiple records with the following query, ultimately using MongoMapper and the Mongo ruby driver.
db.foo.update({event_id: { $in: [1,2]}}, {$inc: {visit:1}}, true, true)
This works fine if all the records exist, but does not create new records for records that do not exist. The following command has the desired effect from the shell, but is probably not ideal from the ruby driver.
[1,2].forEach(function(id) {db.foo.update({event_id: id}, {$inc: {visit:1}}, true, true) });
I could loop through each id I want to insert from within ruby, but that would necessitate a trip to the database for each item. Is there a way to upsert multiple items from the ruby driver with only a single trip to the database? What's the best practice here? Using mongomapper and the ruby driver, is there a way to send multiple updates in a single batch, generating something like the following?
db.foo.update({event_id: 1}, {$inc: {visit:1}}, true); db.foo.update({event_id: 2}, {$inc: {visit:1}}, true);
Sample Data:
Desired data after command if two records exist.
{ "_id" : ObjectId("4d6babbac0d8bb8238d02099"), "event_id" : 1, "visit" : 11 }
{ "_id" : ObjectId("4d6baf56c0d8bb8238d0209a"), "event_id" : 2, "visit" : 2 }
Actual data after command if two records exist.
{ "_id" : ObjectId("4d6babbac0d8bb8238d02099"), "event_id" : 1, "visit" : 11 }
{ "_id" : ObjectId("4d6baf56c0d8bb8238d0209a"), "event_id" : 2, "visit" : 2 }
Desired data after command if only the record with event_id 1 exists.
{ "_id" : ObjectId("4d6babbac0d8bb8238d02099"), "event_id" : 1, "visit" : 2 }
{ "_id" : ObjectId("4d6baf56c0d8bb8238d0209a"), "event_id" : 2, "visit" : 1 }
Actual data after command if only the record with event_id 1 exists.
{ "_id" : ObjectId("4d6babbac0d8bb8238d02099"), "event_id" : 1, "visit" : 2 }
This - correctly - will not insert any records with event_id 1 or 2 if they do not already exist
db.foo.update({event_id: { $in: [1,2]}}, {$inc: {visit:1}}, true, true)
This is because the objNew part of the query (see http://www.mongodb.org/display/DOCS/Updating#Updating-UpsertswithModifiers) does not have a value for field event_id. As a result, you will need at least X+1 trips to the database, where X is the number of event_ids, to ensure that you insert a record if one does not exist for a particular event_id (the +1 comes from the query above, which increases the visits counter for existing records). To say it in a different way, how does MongoDB know you want to use value 2 for the event_id and not 1? And why not 6?
W.r.t. batch insertion with ruby, I think it is possible as the following link suggests - although I've only used the Java driver: Batch insert/update using Mongoid?
What you are after is the Find and Modify command with the upsert option set to true. See the example from the Mongo test suite (same one linked to in the Find and Modify docs) for an example that looks very much like what you describe in your question.
I found a way to do this using the eval operator for server-side code execution. Here is the code snippit:
def batchpush(body, item_opts = {})
#batch << {
:body => body,
:duplicate_key => item_opts[:duplicate_key] || Mongo::Dequeue.generate_duplicate_key(body),
:priority => item_opts[:priority] || #config[:default_priority]
}
end
def batchprocess()
js = %Q|
function(batch) {
var nowutc = new Date();
var ret = [];
for(i in batch){
e = batch[i];
//ret.push(e);
var query = {
'duplicate_key': e.duplicate_key,
'complete': false,
'locked_at': null
};
var object = {
'$set': {
'body': e.body,
'inserted_at': nowutc,
'complete': false,
'locked_till': null,
'completed_at': null,
'priority': e.priority,
'duplicate_key': e.duplicate_key,
'completecount': 0
},
'$inc': {'count': 1}
};
db.#{collection.name}.update(query, object, true);
}
return ret;
}
|
cmd = BSON::OrderedHash.new
cmd['$eval'] = js
cmd['args'] = [#batch]
cmd['nolock'] = true
result = collection.db.command(cmd)
#batch.clear
#pp result
end
Multiple items are added with batchpush(), and then batchprocess() is called. The data is sent as an array, and the commands are all executed. This code is used in the MongoDequeue GEM, in this file.
Only one request is made, and all the upserts happen server-side.