I have a problem to serialize a json from a list of object
My goal is to have this format =>
var tag =
{
RCP: {name: "Dossier à présenter en RCP", type: "checkbox", events: {change: function(e) { console.log(e.data); console.log(e); } }, callback: function(key, opt){ console.log("key : " + key); console.log(opt); alert(opt.$trigger.attr("id")); }},
COL: {name: "Dossier à présenter en colloque", type: "checkbox", callback: function(key, opt){ console.log("key : " + key); console.log(opt); alert(opt.$trigge.attr("id")); }},
COM: {name: "Commentaire", type: "textarea", callback: function(key, opt){ console.log("key : " + key); console.log(opt); alert(opt.$trigge.attr("id")); }}
};
I'm using EF to retrieve the data as this :
var list = (from e in l_entities.TAG
where e.tag_site_code.Trim() == siteCode.Trim()
select new CvrTag
{
Id = e.tag_id,
Name = e.tag_libelle,
Type = e.tag_site_code
}
).ToList();
But I retrieve a classic Array when I use JsonConvert.SerializeObject(list).
So my question is :
- How to have braces instead array's brackets
- How to have an id (ie: RCP or COL) before the json object without quotes
- Same to inside json object (ie: name or type)
Thanks for your help
Since you are invoking ToList(), your serialization will be a list/array. If you want an object instead, use ToDict():
var dict = (from e in l_entities.TAG
where e.tag_site_code.Trim() == siteCode.Trim()
select new CvrTag
{
Id = e.tag_id,
Name = e.tag_libelle,
Type = e.tag_site_code
}
).ToDict(t => t.Id);
Related
My array data:
data = [
{ field: { name:"name1", title:"title1" } },
{ field: { name:"name2", title:"title2" } },
{ field: { name:"name3", title:"title3" } }
];
I want to write name fields like this:
Expected Output
name1.name2.name3
I need join these object's specified field values but I don't know how to get them like this.
What I tried and failed =>
data | selectattr("field") | selectattr("name") | join(".") }}
selectattr-filter only filter data elements. Therefore, when you apply selectattr('name'), nunjucks try to filter data by elements having name-field (none of them) and returns the empty result.
The simplest way to achive name1.name2.name3 is to use a custom filter
const nunjucks = require('nunjucks');
const env = nunjucks.configure();
env.addFilter('map', function (arr, prop, ...etc) {
const f = typeof prop == 'function' ?
prop : typeof env.filters[prop] == 'function' ?
env.filters[prop] : (e) => e[prop];
return arr instanceof Array && arr.map(e => f(e, ...etc)) || arr;
});
const data = [
{field: {name: "name1", title: "title1"}},
{field: {name: "name2", title: "title2"}},
{field: {name: "name3", title: "title3"}}
];
const html = env.renderString(`{{ data | map('field') | map('name') | join('.') }}`, {data});
console.log(html);
I am learning flutter and trying to parse a json which is array or json objects like this.
[
{
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
{
"albumId": 1,
"id": 2,
"title": "reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796"
},]
And here is my fetch function which fetches this data from server.
fetch() async{
var client = new http.Client();
try {
var uriResponse = await
client.get('https://jsonplaceholder.typicode.com/photos');
if(uriResponse.statusCode == 200){
var data = json.decode(uriResponse.body);//data is array of objects
List<Photo> pics= data.map((Map<String,dynamic> model)=> Photo.fromJson(model)).toList();
setState(() {
photos = data;
_isLoading = false;
});
}
} finally {
client.close();
}
}
But the line ;
List<Photo> pics= data.map((Map<String,dynamic> model)=> Photo.fromJson(model)).toList();
gives me error that:
ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '(Map<String, dynamic>, dynamic) => Photo' is not a subtype of type '(dynamic) => dynamic' of 'f'
Here is my Photo PODO class.
class Photo {
final int id;
final String title;
final String url;
final String thumbnailUrl;
Photo({this.id, this.title,this.url, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'] as int,
title: json['title'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
url: json['url'] as String,
);
}
}
What i am doing wrong in the above code? Thanx in advance !
You can use quicktype it lets you copy in your JSON string and generates the Dart Objects
In my project I have done like this and its working
pics = (data as List).map((model) => Photo.fromJson(model)).toList();
Try using
pics = data.map((i)=>Photo.fromJson(i)).toList();
You are receiving an json array and not json object from server
try this if it didnt work make sure to print the the response body
Iterable<dynamic> l = json.decode(uriResponse.body);
List<Post> posts = l.map((model) => Post.fromJson(model)).toList();
I'm struggling with passing the csv strings via ViewBag in the correct format.
I know the result should be like ["Blue","Brown","Green"] but my script is generated as [Blue,Brown,Green] instead.
And then I get the Uncaught ReferenceError : Blue is not defined.
How can I format it in my controller to pass in the correct way?
This is my code in the controller
public ActionResult Index()
{
List<string> teamsList = new List<string>();
List<string> salesCount = new List<string>();
foreach (var team in Db.Teams)
{
teamsList.Add(team.Name);
int count = Db.LeadCampaigns.Count(i => Db.Agents.FirstOrDefault(a => a.AgentId == i.AgentId).TeamId == team.TeamId && i.LeadStatusId == Db.LeadStatuses.FirstOrDefault(s => s.Name == "SALE").LeadStatusId);
salesCount.Add(count.ToString());
}
ViewBag.SaleCount_List = string.Join(",", salesCount);
ViewBag.TeamName_List = string.Join(",", teamsList);
return View();
}
And here is my script in the view.
<script>
var barChartData =
{
labels: [#Html.Raw(ViewBag.TeamName_List)],
datasets: [{
label: 'TeamWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [#ViewBag.SaleCount_List]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'bar',
data: barChartData,
options:
{
title:
{
display: true,
text: "TeamWise Sales Count"
},
responsive: true,
maintainAspectRatio: true
}
});
}
Your plugin expects an array of values, but your passing it a string by using String.Join().
Pass the array using
ViewBag.SaleCount_List = salesCount;
ViewBag.TeamName_List = teamsList;
(or better pass a view model with 2 IEnumerable<string> properties) and then convert it to a jacascript array
var saleCounts = #Html.Raw(Json.Encode(ViewBag.SaleCount_List))
var teamNames = #Html.Raw(Json.Encode(ViewBag.TeamName_List))
var barChartData =
{
labels: teamNames,
datasets: [{
....
],
borderWidth: 2,
data: saleCounts
}]
};
Using your current syntax:
const string quote = "\"";
foreach (var team in Db.Teams)
{
teamsList.Add(quote + team.Name + quote);
int count = Db.LeadCampaigns.Count(i => Db.Agents.FirstOrDefault(a => a.AgentId == i.AgentId).TeamId == team.TeamId && i.LeadStatusId == Db.LeadStatuses.FirstOrDefault(s => s.Name == "SALE").LeadStatusId);
salesCount.Add(count.ToString());
}
My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.
The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.
I have the same issue that the one answered here : Transliteration in typeahead.js
But I can't use the workaround in the answer because the list of suggestion is dynamic !
Is there a way to let the user use non-ascii character (é,à,è,ë,etc..) in their query ?
This is the solution a found :
HTML
$('.typeahead').typeahead(
{
minLength: 3,
},
{
name: 'place',
displayKey: 'city',
source: function (query, process) {
return $.get("{% url 'profil:search_place_request' search_term='user-query' %}".replace('user-query', query), { query: query }, function (data) {
objects = [];
$.each(data, function(i, object) {
objects.push({
city : object.city,
zipcode : object.zipcode,
id : object.id,
});
});
return process(objects);
});
}
}
);
View
#login_required
def search_place_request(request, search_term):
search_term = search_term.encode("utf-8")
response, response_dict = selfcare.libs.core.utils.MyAPIRequests.get("place/?term={}".format(search_term))
if response.ok :
log.info('[profil] request GET places. Search term : {}, USER : {}'.format(search_term, request.user.username))
return HttpResponse(json.dumps(response_dict['results']), content_type="application/json")
else :
log.warning('[profil] request DELETE customer address failed. Status code : {}, USER: {}'.format(response.status_code, request.user.username))
return HttpResponse("", content_type="application/json")
return HttpResponse("", content_type="application/json")
I explicitly encode in utf8 in my view, and it did the trick !