How to convert Json to Map in Dart/Flutter? - json

I have json data but i need to convert the json to Map in dart/flutter.
The json data is :
{"kabupaten": [
{
"jec_kabupaten_id": "71",
"jec_propinsi_id": "8",
"name": "Aceh Barat"
},
{
"jec_kabupaten_id": "76",
"jec_propinsi_id": "8",
"name": "Aceh Barat Daya"
},
{
"jec_kabupaten_id": "91",
"jec_propinsi_id": "9",
"name": "Medan"
},
{
"jec_kabupaten_id": "92",
"jec_propinsi_id": "9",
"name": "Sinabung"
}
]}
I want to convert to this Map with dart/flutter:
{
"8":{
"71":"Aceh Barat",
"76":"Aceh Barat Daya",
"68":"Aceh Besar"
},
"9":{
"91":"Medan",
"92":"Sinabung"
}
}

It is possible to transform the data using fold for example.
void main() {
const data = {
"kabupaten": [
{
"jec_kabupaten_id": "71",
"jec_propinsi_id": "8",
"name": "Aceh Barat",
},
{
"jec_kabupaten_id": "76",
"jec_propinsi_id": "8",
"name": "Aceh Barat Daya",
},
{
"jec_kabupaten_id": "91",
"jec_propinsi_id": "9",
"name": "Medan",
},
{
"jec_kabupaten_id": "92",
"jec_propinsi_id": "9",
"name": "Sinabung",
},
],
};
final result = data['kabupaten']?.fold<Map<String, Map<String, String>>>(
{},
(prev, elem) => prev
..[elem['jec_propinsi_id']!] ??= {}
..[elem['jec_propinsi_id']!]![elem['jec_kabupaten_id']!] = elem['name']!,
);
print(result);
}
An alternative would be to build up the result in a for loop:
final result = <String, Map<String, String>>{};
for (final elem in data['kabupaten'] ?? []) {
result[elem['jec_propinsi_id']!] ??= {};
result[elem['jec_propinsi_id']!]![elem['jec_kabupaten_id']!] = elem['name']!;
}

Related

Flutter - How to read json object with two lists?

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.

Flutter: parsing json response that has multiple keys

I'm trying to get the values of these keys from this json response:
{
"pro": {
"groups": [
"1": {
"name": "Base",
"fields": [
{
"id": 3,
"value": {
"raw": "Name",
}
},
{
"id": 4,
"value": {
"raw": "avatar",
}
},
]
},
"2": {
"name": "Base",
"fields": [
{
"id": 6,
"value": {
"raw": "Name",
}
},
{
"id": 7,
"value": {
"raw": "avatar",
}
},
]
}
]
}
}
I could get the values "name": "Base"
json['pro']['groups']["1"]['name'],
But I can't get the values of key "raw".
How can I get the values of key "raw"?
The values of fields are a list, so you will get a list of raw values:
List<String> raw = json['pro']['groups']['1']['fields'].map((v) => v['value']['raw'];
Also, it seems like groups is an array but as an object? then you can do something like this:
List<String> raw = [];
Map<String, dynamic> groups = json['pro']['groups'];
for (var key in groups.keys) {
raw.add(groups[key]['fields'].map((v) => v['value']['raw']);
}
or
List<String> raw = groups.keys.map((key) => groups[key]['fields'].map((v) => v['value']['raw']);
I haven't tested the code, but hopefully, it works as expected :)
first thing first. your json is invalid.
try to paste your json here it will show why is your json is invalid
after you fix the json the new structure json will be looked like this
{
"pro": {
"groups": [
{
"name": "Base",
"fields": [
{
"id": 3,
"value": {
"raw": "Name",
}
},
{
"id": 4,
"value": {
"raw": "avatar",
}
},
]
},
{
"name": "Base",
"fields": [
{
"id": 6,
"value": {
"raw": "Name",
}
},
{
"id": 7,
"value": {
"raw": "avatar",
}
},
]
}
]
}
}
and then in order to grab the value of raw, you have to parse the json first using jsonDecode(), then you can use something like this:
Map<String, dynamic> groupOne = json['pro']['groups'][0];
Map<String, dynamic> groupOneFieldOne = groupOne['fields'][0];
print(groupOneFieldOne['value']['raw']);
but that's just an example. if you want to access them easily you can use .map() like this:
List<Map<String, dynamic>> groups = json['pro']['groups'];
groups.map(
(Map<String, dynamic> group) => (group['fields'] as List<dynamic>).map(
(dynamic field) => field['value']['raw'],
),
);
that's it! if you want to ask anything just put a comment ;)
you can copy and paste on dartpad
List<Map<String, dynamic>> groups = json['pro']['groups'];
print(groups.map(
(Map<String, dynamic> group) => (group['fields'] as List<dynamic>).map(
(dynamic field) => field['value']['raw'],
),
));
}
Map<String, dynamic> json = {
"pro": {
"groups": [
{
"name": "Base",
"fields": [
{
"id": 3,
"value": {
"raw": "Name",
}
},
{
"id": 4,
"value": {
"raw": "avatar",
}
},
]
},
{
"name": "Base",
"fields": [
{
"id": 6,
"value": {
"raw": "Name",
}
},
{
"id": 7,
"value": {
"raw": "avatar",
}
},
]
}
]
}
};

Error while Adding JSON data to the list in flutter

Below is the JSON data retrieved successfully from the server in flutter application
{
"error": "false",
"notification": [
{
"rn": "1",
"id": "224",
"company_details": {
"code": "2",
}
},
{
"rn": "2",
"id": "219",
"company_details": {
"code": "3",
}
},
{
"rn": "3",
"id": "213",
"company_details": {
"code": "3",
}
},
{
"rn": "4",
"id": "209",
"company_details": {
"code": "4",
}
},
{
"rn": "5",
"id": "204",
"company_details": {
"code": "3",
}
},
{
"rn": "6",
"id": "199",
"company_details": {
"code": "3",
}
},
{
"rn": "7",
"id": "193",
"company_details": {
"code": "3",
}
}
],
}
The code used here is below
List notificationsList;
getnotifications(int page) async {
Map data = {
'user_id': โ€œVICKY,
"page":page.toString()
};
var response = await http.post(companyorders, body: data);
if(response.statusCode == 200) {
jsonResponse = json.decode(response.body);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
String errorcheck = jsonResponse['error'];
companyDetail = NotificationModel.fromJson(json.decode(response.body));
companyDetail = NotificationModel.fromJson(json.decode(response.body));
print('names of companies');
print(companyDetail.content);
List list = jsonResponse['notification'];
notificationsList.add(list);
}
}
When I tried to add the list to the notificationsList I got the below error
Unhandled Exception: NoSuchMethodError: The method 'add' was called on
null. Receiver: null Tried calling: add(Instance(length:7) of
'_GrowableList')
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
I want to add the data retrieved to the notificationsList, how should I do that
You need to initialize notificationsList:
List notificationsList = [];
Also since list is an iterable therefore use addAll()

Unmarshal deeply nested json in golang

I have an ugly way of unmarshalling the following json, but it requires much manual work. I am looking for a more programmatic way to obtain the various team names, if I didn't know how many teams exactly there were originally. It's truly one of the most poorly structured api's I've come across.
data := []byte(`{
"fantasy_content": {
"copyright": "Data provided by Yahoo! and STATS, LLC",
"league": [
{
"allow_add_to_dl_extra_pos": 0,
"current_week": "1",
"draft_status": "predraft",
"edit_key": "1",
"end_date": "2017-12-25",
"end_week": "16",
"game_code": "nfl",
"is_cash_league": "0",
"is_pro_league": "0",
"league_id": "XXXXX",
"league_key": "XXXX",
"league_type": "private",
"league_update_timestamp": null,
"name": "XXXXXX",
"num_teams": 14,
"renew": "XXXX",
"renewed": "",
"scoring_type": "head",
"season": "2017",
"short_invitation_url": "XXXXX",
"start_date": "2017-09-07",
"start_week": "1",
"url": "XXXXXX",
"weekly_deadline": ""
},
{
"teams": {
"0": {
"team": [
[
{
"team_key": "XXXX"
},
{
"team_id": "1"
},
{
"name": "XXXXX"
},
[],
{
"url": "XXXXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"XXX"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXXX",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"is_commissioner": "1",
"manager_id": "1",
"nickname": "Andrew"
}
}
]
}
]
]
},
"1": {
"team": [
[
{
"team_key": "XXXXX"
},
{
"team_id": "2"
},
{
"name": "XXXXX"
},
[],
{
"url": "XXXXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "XXXX"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXX#yahoo.com",
"guid": "XXXX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "2",
"nickname": "Andrew"
}
},
{
"manager": {
"email": "XXX#yahoo.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"is_comanager": "1",
"manager_id": "15",
"nickname": "XX"
}
}
]
}
]
]
},
"10": {
"team": [
[
{
"team_key": "XXX"
},
{
"team_id": "11"
},
{
"name": "XXX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://s.yimg.com/dh/ap/fantasy/nfl/img/icon_01_100.png"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX#gmail.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "11",
"nickname": "XX"
}
}
]
}
]
]
},
"2": {
"team": [
[
{
"team_key": "371.l.102542.t.3"
},
{
"team_id": "3"
},
{
"name": "XXX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/3"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/5603/30147468023_1c705edb29_192sq.jpg?ct=fantasy"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXgmail.com",
"guid": "XXXX",
"image_url": "https://s.yimg.com/wv/images/6c93ed606f742d4c075bc091633cc072_64.jpg",
"manager_id": "3",
"nickname": "XX"
}
}
]
}
]
]
},
"3": {
"team": [
[
{
"team_key": "371.l.102542.t.4"
},
{
"team_id": "4"
},
{
"name": "XX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/4"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://s.yimg.com/dh/ap/fantasy/nfl/img/icon_10_100.png"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX#yahoo.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "4",
"nickname": "XX"
}
}
]
}
]
]
},
"8": {
"team": [
[
{
"team_key": "XXX"
},
{
"team_id": "9"
},
{
"name": "XxX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/9"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/8393/28682944304_33bda49603_192sq.jpg?ct=fantasy"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX",
"guid": "XXX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "9",
"nickname": "XXX"
}
}
]
}
]
]
},
"count": 14
}
}
],
"refresh_rate": "60",
"time": "110.55207252502ms",
"xml:lang": "en-US",
"yahoo:uri": "/fantasy/v2/league/XXXX/teams"
}
}`)
The following works, but it's a hassle and I have to hard code the different struct values per team, to get data for that team.
type TeamApi_ struct {
TeamKey string `json:"team_key"`
TeamId string `json:"team_id"`
Name string `json:"name"`
}
type LeaguesApi struct {
NumTeams int `json:"num_teams"`
TeamsApi struct {
Zero struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"0"`
One struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"1"`
Two struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"2"`
Three struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"3"`
} `json:"teams"`
}
type LeagueApiResult struct {
FantasyContent struct {
LeagueApi []LeaguesApi `json:"league"`
} `json:"fantasy_content"`
}
var Result LeagueApiResult
err := json.Unmarshal(data, &Result)
if err != nil {
fmt.Println(err)
}
fmt.Println(Result.FantasyContent.LeagueApi[1].TeamsApi.One.TeamsApi_[0][2].Name)
You probably want to use a custom JSON unmarshaller for this. You can see an example of how to use one here: http://choly.ca/post/go-json-marshalling/
Since the data is structured the way it is, with the teams section both containing teams and the count field, you'll likely need a fair bit of manual logic in there.
First, you can start by defining the League:
type League struct {
AllowAddToDlExtraPos int `json:"allow_add_to_dl_extra_pos,omitempty"`
CurrentWeek string `json:"current_week,omitempty"`
DraftStatus string `json:"draft_status,omitempty"`
EditKey string `json:"edit_key,omitempty"`
EndDate string `json:"end_date,omitempty"`
EndWeek string `json:"end_week,omitempty"`
GameCode string `json:"game_code,omitempty"`
IsCashLeague string `json:"is_cash_league,omitempty"`
IsProLeague string `json:"is_pro_league,omitempty"`
LeagueID string `json:"league_id,omitempty"`
LeagueKey string `json:"league_key,omitempty"`
LeagueType string `json:"league_type,omitempty"`
LeagueUpdateTimestamp interface{} `json:"league_update_timestamp,omitempty"`
Name string `json:"name,omitempty"`
NumTeams int `json:"num_teams,omitempty"`
Renew string `json:"renew,omitempty"`
Renewed string `json:"renewed,omitempty"`
ScoringType string `json:"scoring_type,omitempty"`
Season string `json:"season,omitempty"`
ShortInvitationURL string `json:"short_invitation_url,omitempty"`
StartDate string `json:"start_date,omitempty"`
StartWeek string `json:"start_week,omitempty"`
URL string `json:"url,omitempty"`
WeeklyDeadline string `json:"weekly_deadline,omitempty"`
Teams []Team `json:"-"`
}
Next, we can define the Team structure the way we want it to look.
type Team struct {
// Declare the fields of a Team
}
And finally, we declare a custom unmarshal function for the League.
func (l *League) UnmarshalJSON(data []byte) error {
type Alias League
aux := &struct {
*Alias
Teams map[string]interface{} `json:"teams"`
}{
Alias: (*Alias)(l),
}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
var teams []Team
for num, team := range aux.Teams {
// Add your code to parse each of the teams from the
// map you declared above.
}
l.Teams = teams
return nil
}
The unmarshal function will be called by Golangs json library automatically when it hits the League structure inside the LeagueApiResult.

How to get particular details based on category using angular 2

I have given below is my json object how to get citydetails where city_id=50?
{
"status": 0,
"message": "success",
"citydetails": [
{
"city_id": "50",
"city_name": "Pune"
},
{
"city_id": "53",
"city_name": "Mumbai"
},
{
"city_id": "50",
"city_name": "Pune"
},
{
"city_id": "52",
"city_name": "Banglore"
},
{
"city_id": "50",
"city_name": "Pune"
}
]
}
let json = {
"status":0,
"message":"success",
"citydetails":[
{
"city_id":"50",
"city_name":"Pune"
},
{
"city_id":"53",
"city_name":"Mumbai"
},
{
"city_id":"50",
"city_name":"Pune"
},
{
"city_id":"52",
"city_name":"Banglore"
},
{
"city_id":"50",
"city_name":"Pune"
}]
};
Assuming above in your JSON, below code will filter the city objects.
let filteredCities = json.citydetails.filter(data => {
return data.city_id === "50";
});
filteredCities object will contain only the filtered city objects as an Array