Flutter - How to read json object with two lists? - json

I have a json like this:
{
"data": [
{
"id": "99412",
"type": "post_list_item",
"attributes": {
"message": "#:user/3 \n#:user/77 \n#:user/52 #:user/3921 #:user/267 #:user/5 \n\nWhich sector will outperform in 2023 ???",
"visibility": "public_visible",
"created_at": "2023-01-07T14:38:00.691+05:30",
"updated_at": "2023-01-07T14:38:00.779+05:30",
"meta_info": null,
"type": "Post",
"likes_count": 8,
"replies_count": 2,
"widgets_data": [],
"is_liked": false,
"is_bookmarked": false,
"is_deleted": false,
"share_count": null
},
"relationships": {
"user": {
"data": {
"id": "86806",
"type": "user"
}
},
"poll": {
"data": {
"id": "483",
"type": "poll"
}
},
"tagged_users": {
"data": [
{
"id": "3",
"type": "user"
},
{
"id": "5",
"type": "user"
},
{
"id": "52",
"type": "user"
},
{
"id": "77",
"type": "user"
},
{
"id": "267",
"type": "user"
},
{
"id": "3921",
"type": "user"
}
]
},
"tagged_companies": {
"data": []
},
"tagged_topics": {
"data": []
},
"tagged_instruments": {
"data": []
},
"stories": {
"data": []
},
"attachments": {
"data": []
},
"media_files": {
"data": []
}
}
},
{
"id": "99548",
"type": "post_list_item",
"attributes": {
"message": "๐“๐จ๐ฉ ๐ง๐ž๐ฐ๐ฌ ๐ญ๐จ๐๐š๐ฒ๐ŸŽŒ \n\n๐Ÿ“SGX Nifty up by 132 pts indicating a strong open
today. FIIs sold Rs 29 Bn while DIIs bought Rs 10.8 Bn of stocks on Friday.\n\n๐Ÿ“India surpasses Japan to become world's 3rd largest auto market in 2022: SIAM report\n\n๐Ÿ“Dr Lal PathLabs, leader in North India, expands in West India. Subsidiary opens apex lab in Mumbai - all nearby samples to be tested here instead of Delhi (positive).\n\n๐Ÿ“IL&FS pays 5 PSU Banks 87% of their โ‚น1,500 crore dues. Canara, Union Bank, Central, Punjab & Sind Bank.\n\n๐Ÿ“EV scooter co. Ather Energy to achieve $1 billion in revenue in 2023 and turn profitable in few years. Beneficiary: Hero Motors\n\n๐Ÿ“Outstanding dues by power distributors (discoms) to producers (gencos) has nearly halved to Rs 62,681 cr in last 1 year. Benficiary: PFC, REC (but priced in).\n\n๐Ÿ“Solar panel manufacters boost production as costs fall for polysilicon and wafer (RM for solar cells). Positive for Sterling Wilson Renewables, Borosil Renewables.\n\n1/2",
"visibility": "public_visible",
"created_at": "2023-01-09T09:05:41.226+05:30",
"updated_at": "2023-01-09T09:05:41.277+05:30",
"meta_info": null,
"type": "Post",
"likes_count": 4,
"replies_count": 1,
"widgets_data": [],
"is_liked": false,
"is_bookmarked": false,
"is_deleted": false,
"share_count": null
},
"relationships": {
"user": {
"data": {
"id": "83681",
"type": "user"
}
},
"poll": {
"data": null
},
"tagged_users": {
"data": []
},
"tagged_companies": {
"data": []
},
"tagged_topics": {
"data": []
},
"tagged_instruments": {
"data": []
},
"stories": {
"data": []
},
"attachments": {
"data": []
},
"media_files": {
"data": []
}
}
}, ],
"included": [
{
"id": "86806",
"type": "user",
"attributes": {
"display_name": "Ravi Gupta",
"username": "ravigupta132",
"dp_thumbnail": "/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBZ2E4IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--763b2ccc4372862bb99de6620aa9fe9661693603/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdCem9MWm05eWJXRjBTU0lJYW5CbkJqb0dSVlE2RkhKbGMybDZaVjkwYjE5c2FXMXBkRnNIYVFHQWFRR0EiLCJleHAiOm51bGwsInB1ciI6InZhcmlhdGlvbiJ9fQ==--7b4a499a9ad66d05dd5deec71f9adfd36a29feb5/image_cropper_1672468958147.jpg",
"market_view": "neutral"
},
"relationships": {}
},
{
"id": "483",
"type": "poll",
"attributes": {
"question": "#:user/3 \n#:user/77 \n#:user/52 #:user/3921 #:user/267 #:user/5 \n\nWhich sector will outperform in 2023 ???",
"options": [
"Metal",
"PSU banks",
"IT",
"Infrastructure"
],
"vote_count": 52,
"grouped_count": null,
"ends_at": "2023-01-14T14:38:01.760+05:30",
"my_vote": null,
"is_expired": false
},
"relationships": {
"base_post": {
"data": {
"id": "99412",
"type": "post"
}
}
}
}, ]
}
Basically, 2 lists in an object.
I am unable to deserialize this data. How do I de-serialize this data to get 2 lists? I need to get data based on a common id.
This is what I have currently (WIP):
Future<List<Datum>> getPostData() async {
try {
Response response = await _dio.get(url);
var jsonData = response.data;
//Map<String, dynamic> postMap = response.data;
final someMappedObjectList = <Datum>[];
for (var map in jsonData["data"]) {
Datum someObject = Datum(
id: map["id"],
type: map["type"],
attributes: map["attributes"],
relationships: map["relationships"]);
//final someObject = Datum.fromJson(map);
someMappedObjectList.add(someObject);
}
//List<dynamic> listDatum = postMap["data"].toList();
//List<Datum> listDatum = Datum.fromJson(jsonData["data"]) as List<Datum>;
return someMappedObjectList;
} //
catch (e) {
print(e);
return [];
}
}
Future<List> getPostIncluded() async {
try {
Response response = await _dio.get(url);
var jsonData = response.data;
Map<String, dynamic> postMap = response.data;
List<dynamic> listIncluded = postMap["included"].toList();
return listIncluded;
} //
catch (e) {
print(e);
return [];
}
}

Especially for something this complex, I strongly suggest using the json_serializable package. It will save you quite a bit of trouble in the long term.

Related

How to match the no of responses returned with a value displayed in the response body

I have the below response in my postman Body .
{
"count": 3,
"next": null,
"previous": null,
"results": [
{
"id": "c2004ef952894279920417ba8283d26a",
"name": "attrib_inv_bu",
"modified_date": "2020-07-06T02:15:06.839577",
"display_group": {
"id": "attr_dis_267a405426184764816e504b4f0a565b",
"name": "Custom"
},
"api_url": "https://abc.xyz.com/api/v1/attributes/attr_c2004ef952894279920417ba8283d26a/",
"url": "https://abc.xyz.com/manage/matter_attributes/2707/"
},
{
"id": "c2004ef95289422324232a8283d26a",
"name": "attrib_idsdw_sfs",
"modified_date": "2020-07-06T02:11:06.839577",
"display_group": {
"id": "attr_dis_267a4054261dfsf64816e504b4f0a565b",
"name": "Custom"
},
"api_url": "https://abc.xyz.com/api/v1/attributes/attr_c2004ef952894279920417ba8ssd3d26a/",
"url": "https://abc.xyz.com/manage/matter_attributes/2709/"
},
{
"id": "c2004ef9we22e2e8283d26a",
"name": "attrib_iasa_ac",
"modified_date": "2020-07-06T02:17:06.839577",
"display_group": {
"id": "attr_dis_267a405426184764816e5dsds4f0a565b",
"name": "Custom"
},
"api_url": "https://abc.xyz.com/api/v1/attributes/attr_c2004ef952894279920417ba8283sds26a/",
"url": "https://abc.xyz.com/manage/matter_attributes/2708/"
}
]
}
I want to assert whether I have 3 different ids match with the count 3 that is displayed in the body.
res = pm.response.json()
res.count === res.results.length
you can use in expect as :
pm.expect(res.count).to.be.equal(res.results.length)
If you want to verify they are indeed unique:
let resultidlits = []
result.forEach((a) => {
resultidlits.includes(a.id)? null : resultidlits.push(a.id)
})
pm.expect(res.count).to.be.equal(resultidlits.length)

How to filter with console.log JSON?

I need to filter in the console.log the data that I get from the json that I show in the image. How could I do it?
Code
This is my .JSON
[
{
"category": "FORMULARIOS",
"items": [
{
"label": "Botones",
"url": "ui-botones"
},
{
"label": "Inputs",
"url": "ui-inputs"
}
]
},
{
"category": "CORREOS",
"items": [
{
"label": "Facturas",
"url": "ui-facturas"
},
{
"label": "Movimientos",
"url": "ui-movimientos"
}
]
},
{
"category": "ALERTAS",
"items": [
{
"label": "Toast",
"url": "ui-toast"
},
{
"label": "Toolips",
"url": "ui-toolips"
}
]
}
]
You can do like this:
var yourJSON ="......";
var newData = filterData('CORREOS');
function filterData(catalogyName) {
return yourJSON.filter(object => {
return object['category'] == catalogyName;
});
}
console.log(newData);

Unique sub-Json of a Json

let me start from a JSon object like
[
{
"id": 32837732,
"composer": {
"id": 536,
"name": "Francis Poulenc"
},
"title": "Of Thee I Sing: Overture (radio version)"
},
{
"id": 32837735,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : I. Allegro"
},
{
"id": 32837739,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : II. Adagio"
}
]
is it possible to get, in a clean, declarative way, a Json like
{
'composer': [
{
'id': '536',
'name': 'Francis Poulenc'
},
{
'id': '245',
'name': 'George Gershwin'
},
]
}
That is the unique sub-values for each composer (id and name)?
var arr= [
{
"id": 32837732,
"composer": {
"id": 536,
"name": "Francis Poulenc"
},
"title": "Of Thee I Sing: Overture (radio version)"
},
{
"id": 32837735,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : I. Allegro"
},
{
"id": 32837739,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : II. Adagio"
}
];
var composers=[];
arr.forEach(function(arrElem){
if(arrElem.composer && !composers.some(function(comp) { return comp.id === arrElem.composer.id && comp.name === arrElem.composer.name }))
composers.push(arrElem.composer);
});
alert( JSON.stringify( composers ));

How can I return an array of object based on matching ids?

I am trying to match the ids of two json files and return the matching objects. These are the 2 json files:
{
"een": {
"id": "100",
"title": "Entertainment and stuff"
},
"twee": {
"id": "107",
"title": "Sport for everyone"
},
"drie": {
"id": "108",
"title": "Eating is good"
}
}
This is the second one:
[
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
As a result of the 2 matching idvalues I should get:
[
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false,
"title": "Entertainment and stuff"
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"title": "Sport for everyone"
}
]
I was wondering if there was a fancy way using lodash or something else and do this in a nice compact way?
One possible solution would be to use merge to merge two objects that have the id as the key. This can be done using keyBy on the array and also on the values of the first object. Intersection is used find ids that are in both arrays.
let list1 = {
"een": {
"id": "100",
"title": "Entertainment and stuff"
},
"twee": {
"id": "107",
"title": "Sport for everyone"
},
"drie": {
"id": "108",
"title": "Eating is good"
}
}
let list2 = [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
let o1 = _.keyBy(_.values(list1), 'id');
let o2 = _.keyBy(list2, 'id');
let matchingIds = _.intersection(_.keys(o1), _.keys(o2));
let result = _.chain(o1)
.pick(matchingIds)
.merge(_.pick(o2,matchingIds))
.values()
.value()
Building on #GruffBunny's answer, you want to take his result and filter out those ids that aren't found in o1 and o2.
let o1 = _.keyBy(_.values(list1), 'id'));
let o2 = _.keyBy(list2, 'id');
let idsToPull = _.difference( _.map(o1, 'id'), _.map(o2, 'id')) //["108"]
let merged = _.values(_.merge(o1, o2 ));
let result = _.filter(merged, function(obj){ return _.indexOf(idsToPull, obj.id) === -1 })

Linq to Json using Like Clause

I've got an MVC 3 web app and am returning a JSON object which I would like to use Linq against to limit the result returned to the client jquery.
The Json response takes the following structure:
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
....
I need to return or grab just the json items that have a Name like 'Setting' for example. In the example, this would return just the 2 Json nodes.
My Linq is very limited and what I have is: Settings is where the Json response is stored.
NewtonSoft.Json.Linq.JObject data = NewtonSoft.Json.Linq.JObject.Parse(Settings);
var result = from p in data["Data"]["Items"].Children()
where (p["Result"]["Name"].Contains("Expenses.Help.Tip"))
select new { Name = (string)p["Result"]["Name"], Value = (string)p["Result"]["Value"] };
When I run this I get nothing in my result. Can anyone help and tell me what I'm doing wrong?
Thanks.
Well, I'm not a Json specialist, but I think your Json structure has some problems.
I tried an online parser, and parsing took only the third result... (try to copy past your code in the left window, and look at JS eval.
Instead of
"Items": [
{
"Result": {
},
"Result": {
},
"Result": {
}
}]
you should have each element of Items array (each 'Result') into {}.
"Items": [
{
{"Result": {
}
},
{"Result": {
}
},
{"Result": {
}
}]
I got it to work by changing your Json file to
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
using
var data = JObject.Parse(test)["Data"]["Items"].Children()
.Where(m => m["Result"]["Name"].Value<string>().Contains("Setting"))
.Select(m => new
{
Name = m["Result"]["Name"].Value<string>(),
Value = m["Result"]["Value"].Value<int>()
})
.ToList();