remove nested array from json array - mysql

How do i go about returning only the json without the [] from a Mysql multiple query?
I have this as an SQL Query
app.get('/api/v1/admin/getAllUsers',async function (req,res,next){
try {
if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ') || !req.headers.authorization.split(' ')[1]) {
return res.status(422).json({ message: 'Please Provide Token!' })
}
dbConn.query('select * from fasta_users; select * from fasta_logistics; select * from fasta_admin_users;select * from fasta_riders;', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'users list' });
});
} catch (err) {
next(err);
}
})
having run this, I get this as response :
{
"error": false,
"data": [
[
{
"id": 1,
"fastaUserId": "",
"fullname": "John Qasim",
"email": "j_qasim001#aol.com",
"password": "$2a$12$iAzLsIEcOJpDSSgdUmJBR.e8pWdieUg7N4bFiW0lkgBsQQDA6DwPG",
"state": "Imo",
"role": "Customers",
"city": "Owerri",
"phone_num": "08076631261",
"created_at": "2022-05-17T15:58:26.000Z"
}
],
[
{
"id": 1,
"fastaUserId": "",
"fullname": "alex roman",
"email": "alex.roman#juno.com",
"password": "$2a$12$sXpfYaQQIwoBf1KMaPrgT.PioHY4Y6SXD1lpheDB9EPTwfRtsg1p.",
"state": "Lagos",
"city": "city",
"phone_num": "08111111111",
"company_type": "Registered",
"company_name": "Polaris Shipping Inc.",
"company_regnum": "RC-123456",
"c_license": 1,
"role": "Delivery man",
"l_licensenumber": "LAG-2372328",
"company_address": "150 Wole Madariola Close",
"num_employees": "200",
"company_nature": "Sole Propietorship",
"created_at": "2022-05-17T15:57:41.000Z"
}
],
[
{
"id": 1,
"fastaUserId": "",
"fullname": "John Legend",
"email": "john.legend#gmail.com",
"password": "$2a$12$KrW0YKsJmvlp2z5uF4V10uLIjcPpSl1ba/LiWuiRpaLs/XRmguXDy",
"phone_num": "0188272610",
"avatar": "test_pic",
"role": "Administrator",
"status": "Active",
"created_at": "2022-05-11T18:48:39.000Z"
}
],
[
{
"id": 1,
"Name": "Karen Mitchelle",
"RidersID": "FR-60842",
"Status": "Active",
"email": "k.m.boon#gmail.com",
"password": "$2a$12$PCTK8okWO/ApoNSgXXTIl.oxzwqf.zlHHJaEvxtfxpUrnI1IaGNQC",
"phone": "08128829102",
"No_deliveries": "200",
"rating": "5",
"state": "Lagos",
"city": "Lagos",
"role": "Rider",
"address": "150 Wole Kolawole Str. Lagos Nigeria",
"bike_manufacturer": "Suzuki",
"bike_model": "Suzuki 400",
"bike_year": "2012",
"engine_power": "HP8",
"bike_color": "red",
"license_number": "SMK900-LA",
"license_expiry": "2027-05-01",
"vehicle_id": "LA8373Q2",
"created_at": "2022-05-17T15:59:22.000Z"
}
]
],
"message": "users list"
}
I just want it to return just the json object alone. How is this possible?
Please I need a guide with this,How can I get this resolved? I need a guide with this.
is there a way to make it be like this :
{
"error":false,
"data":{
"id": 1,
"fastaUserId": "",
"fullname": "John Qasim",
"email": "j_qasim001#aol.com",
"password": "$2a$12$iAzLsIEcOJpDSSgdUmJBR.e8pWdieUg7N4bFiW0lkgBsQQDA6DwPG",
"state": "Imo",
"role": "Customers",
"city": "Owerri",
"phone_num": "08076631261",
"created_at": "2022-05-17T15:58:26.000Z",
{
"id": 1,
"fastaUserId": "",
"fullname": "alex roman",
"email": "alex.roman#juno.com",
"password": "$2a$12$sXpfYaQQIwoBf1KMaPrgT.PioHY4Y6SXD1lpheDB9EPTwfRtsg1p.",
"state": "Lagos",
"city": "city",
"phone_num": "08111111111",
"company_type": "Registered",
"company_name": "Polaris Shipping Inc.",
"company_regnum": "RC-123456",
"c_license": 1,
"role": "Delivery man",
"l_licensenumber": "LAG-2372328",
"company_address": "150 Wole Madariola Close",
"num_employees": "200",
"company_nature": "Sole Propietorship",
"created_at": "2022-05-17T15:57:41.000Z"
},
{
"id": 1,
"fastaUserId": "",
"fullname": "John Legend",
"email": "john.legend#gmail.com",
"password": "$2a$12$KrW0YKsJmvlp2z5uF4V10uLIjcPpSl1ba/LiWuiRpaLs/XRmguXDy",
"phone_num": "0188272610",
"avatar": "test_pic",
"role": "Administrator",
"status": "Active",
"created_at": "2022-05-11T18:48:39.000Z"
},
{
"id": 1,
"Name": "Karen Mitchelle",
"RidersID": "FR-60842",
"Status": "Active",
"email": "k.m.boon#gmail.com",
"password": "$2a$12$PCTK8okWO/ApoNSgXXTIl.oxzwqf.zlHHJaEvxtfxpUrnI1IaGNQC",
"phone": "08128829102",
"No_deliveries": "200",
"rating": "5",
"state": "Lagos",
"city": "Lagos",
"role": "Rider",
"address": "150 Wole Kolawole Str. Lagos Nigeria",
"bike_manufacturer": "Suzuki",
"bike_model": "Suzuki 400",
"bike_year": "2012",
"engine_power": "HP8",
"bike_color": "red",
"license_number": "SMK900-LA",
"license_expiry": "2027-05-01",
"vehicle_id": "LA8373Q2",
"created_at": "2022-05-17T15:59:22.000Z"
}
}
}
Edits
My code is Looking like this now :
app.get('/api/v1/admin/getAllUsers',async function (req,res,next){
try {
if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ') || !req.headers.authorization.split(' ')[1]) {
return res.status(422).json({ message: 'Please Provide Token!' })
}
dbConn.query('select * from fasta_users; select * from fasta_admin_users;select * from fasta_riders;', function (error, results, fields) {
if (error) throw error;
const infoz = results.data.map(arr =>arr[0]);
return res.send({ error: false, data: infoz, message: 'users list' });
});
} catch (err) {
next(err);
}
})
It still returns the nested array.

You can user Array#map() and get first user from nested array using Destructuring assignment
Code:
const response = {error: false,data: [[{id: 1,fastaUserId: '',fullname: 'John Qasim',email: 'j_qasim001#aol.com',password: '$2a$12$iAzLsIEcOJpDSSgdUmJBR.e8pWdieUg7N4bFiW0lkgBsQQDA6DwPG',state: 'Imo',role: 'Customers',city: 'Owerri',phone_num: '08076631261',created_at: '2022-05-17T15:58:26.000Z',},],[{id: 1,fastaUserId: '',fullname: 'alex roman',email: 'alex.roman#juno.com',password: '$2a$12$sXpfYaQQIwoBf1KMaPrgT.PioHY4Y6SXD1lpheDB9EPTwfRtsg1p.',state: 'Lagos',city: 'city',phone_num: '08111111111',company_type: 'Registered',company_name: 'Polaris Shipping Inc.',company_regnum: 'RC-123456',c_license: 1,role: 'Delivery man',l_licensenumber: 'LAG-2372328',company_address: '150 Wole Madariola Close',num_employees: '200',company_nature: 'Sole Propietorship',created_at: '2022-05-17T15:57:41.000Z',},],[{id: 1,fastaUserId: '',fullname: 'John Legend',email: 'john.legend#gmail.com',password: '$2a$12$KrW0YKsJmvlp2z5uF4V10uLIjcPpSl1ba/LiWuiRpaLs/XRmguXDy',phone_num: '0188272610',avatar: 'test_pic',role: 'Administrator',status: 'Active',created_at: '2022-05-11T18:48:39.000Z',},],[{id: 1,Name: 'Karen Mitchelle',RidersID: 'FR-60842',Status: 'Active',email: 'k.m.boon#gmail.com',password: '$2a$12$PCTK8okWO/ApoNSgXXTIl.oxzwqf.zlHHJaEvxtfxpUrnI1IaGNQC',phone: '08128829102',No_deliveries: '200',rating: '5',state: 'Lagos',city: 'Lagos',role: 'Rider',address: '150 Wole Kolawole Str. Lagos Nigeria',bike_manufacturer: 'Suzuki',bike_model: 'Suzuki 400',bike_year: '2012',engine_power: 'HP8',bike_color: 'red',license_number: 'SMK900-LA',license_expiry: '2027-05-01',vehicle_id: 'LA8373Q2',created_at: '2022-05-17T15:59:22.000Z',},],],message: 'users list',}
response.data = response.data.map(([user]) => user)
console.log(response)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Also you can use Array#flat()
Code:
const response = {error: false,data: [[{id: 1,fastaUserId: '',fullname: 'John Qasim',email: 'j_qasim001#aol.com',password: '$2a$12$iAzLsIEcOJpDSSgdUmJBR.e8pWdieUg7N4bFiW0lkgBsQQDA6DwPG',state: 'Imo',role: 'Customers',city: 'Owerri',phone_num: '08076631261',created_at: '2022-05-17T15:58:26.000Z',},],[{id: 1,fastaUserId: '',fullname: 'alex roman',email: 'alex.roman#juno.com',password: '$2a$12$sXpfYaQQIwoBf1KMaPrgT.PioHY4Y6SXD1lpheDB9EPTwfRtsg1p.',state: 'Lagos',city: 'city',phone_num: '08111111111',company_type: 'Registered',company_name: 'Polaris Shipping Inc.',company_regnum: 'RC-123456',c_license: 1,role: 'Delivery man',l_licensenumber: 'LAG-2372328',company_address: '150 Wole Madariola Close',num_employees: '200',company_nature: 'Sole Propietorship',created_at: '2022-05-17T15:57:41.000Z',},],[{id: 1,fastaUserId: '',fullname: 'John Legend',email: 'john.legend#gmail.com',password: '$2a$12$KrW0YKsJmvlp2z5uF4V10uLIjcPpSl1ba/LiWuiRpaLs/XRmguXDy',phone_num: '0188272610',avatar: 'test_pic',role: 'Administrator',status: 'Active',created_at: '2022-05-11T18:48:39.000Z',},],[{id: 1,Name: 'Karen Mitchelle',RidersID: 'FR-60842',Status: 'Active',email: 'k.m.boon#gmail.com',password: '$2a$12$PCTK8okWO/ApoNSgXXTIl.oxzwqf.zlHHJaEvxtfxpUrnI1IaGNQC',phone: '08128829102',No_deliveries: '200',rating: '5',state: 'Lagos',city: 'Lagos',role: 'Rider',address: '150 Wole Kolawole Str. Lagos Nigeria',bike_manufacturer: 'Suzuki',bike_model: 'Suzuki 400',bike_year: '2012',engine_power: 'HP8',bike_color: 'red',license_number: 'SMK900-LA',license_expiry: '2027-05-01',vehicle_id: 'LA8373Q2',created_at: '2022-05-17T15:59:22.000Z',},],],message: 'users list',}
response.data = response.data.flat()
console.log(response)

Related

How to combine two different payload in to one schema

How to write the JSON schema for both of the payloads by combining in a single schema alert_type: "change" with alert_sub_type: "check change"
alert_type: "change" with alert_sub_type: "check change"
{
"alert_details": {
"event_date": "2021-04-26T12:30:80Z",
"camount": "789",
"profile": {
"name": {
"first_name": "xxxx",
"last_name": "xxxx",
"middle_name": "xxx"
}
},
"check_cash_date": "2021-04-26",
"profile_address": {
"name": "xxxxx",
"street_address": "xxxxxx",
"city": "xxxx",
"state": "CA",
"zip_code": "90021"
},
"alert_id": {
"id": "abc123",
"subject": "abc123",
"abc_id": "abc123"
}
},
"alert_sub_type": "check change",
"alert_type": "change",
"provider": "ABCD",
"view_date": "2020-11-03T10:15:30Z",
"status": "Read"
}
alert_type : "review" alert_sub_type: "review check"
{
"alert_details": {
"event_date": "2020-11-03T10:15:30Z",
"account_number": "*********xxx",
"check_start_number": "2",
"myprofile": {
"name": {
"first_name": "xxxx",
"last_name": "xxxx",
"middle_name": "M"
}
},
"order_shipped_date": "2021-04-23",
"myprofile_address": {
"name": "xxxxx",
"street_address": "xxxxx",
"city": "xxxx",
"state": "xxxx",
"zip_code": "90021"
},
"quantity_ordered": "12",
"alert_id": {
"id": "abc123",
"subject": "abc123",
"abc_id": "abc123"
}
},
"alert_sub_type": "review Check",
"alert_type": "review",
"provider": "abcd",
"view_date": "2020-11-03T10:15:30Z",
"status": "Read"
}
in this alert_type: "change" with alert_sub_type: "check change" mandatory fields are
camount: ""
profile: ""
check_cash_date: ""
profile_address_name: ""
in the alert_type : "review" alert_sub_type: "review check"
mandatory fields are :
check_cash_date: ""
myprofile: ""
"quantity_ordered"

Accessing the Data in json object

This Works
app.get('/api/v1/admin/getAllUsers',async function (req,res,next){
try {
if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ') || !req.headers.authorization.split(' ')[1]) {
return res.status(422).json({ message: 'Please Provide Token!' })
}
dbConn.query('select * from fasta_users; select * from fasta_admin_users;select Name, email,password,phone,role,status,created_at from fasta_riders;', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results , message: 'users list' });
});
} catch (err) {
next(err);
}
})
It returns the data i want without problems but the Json is Looking like this
{
"error": false,
"data": [
[
{
"id": 1,
"fastaUserId": "",
"fullname": "John Qasim",
"email": "j_qasim001#aol.com",
"password": "$2a$12$iAzLsIEcOJpDSSgdUmJBR.e8pWdieUg7N4bFiW0lkgBsQQDA6DwPG",
"state": "Imo",
"role": "Customers",
"city": "Owerri",
"phone_num": "08076631261",
"created_at": "2022-05-17T14:58:26.000Z"
},
{
"id": 2,
"fastaUserId": "FU-71198",
"fullname": "z",
"email": "z#gmail.com",
"password": "$2a$12$a9ibquFv477e6KL3N49JweVoiSmDXR0UVcM5xCkB39/8loKZ/u0bq",
"state": "z",
"role": "z",
"city": "user",
"phone_num": "z",
"created_at": "2022-05-17T17:57:39.000Z"
}
],
[
{
"id": 1,
"fastaUserId": "",
"fullname": "John Legend",
"email": "john.legend#gmail.com",
"password": "$2a$12$KrW0YKsJmvlp2z5uF4V10uLIjcPpSl1ba/LiWuiRpaLs/XRmguXDy",
"phone_num": "0188272610",
"avatar": "test_pic",
"role": "Administrator",
"status": "Active",
"created_at": "2022-05-11T17:48:39.000Z"
},
{
"id": 2,
"fastaUserId": "FA-76249",
"fullname": "James Hall",
"email": "jameshallblog.com#gmail.com",
"password": "$2a$12$j711FBY441CHwacisjcL9OT9Rjb5Yll8VzdSncKJilC0Pku9i2RP2",
"phone_num": "090865735422",
"avatar": "https://oxfordssocustomerapi.azurewebsites.net/Docs/Users/OIG-00424.jpg",
"role": "Administrator",
"status": "Active",
"created_at": "2022-05-17T17:51:03.000Z"
}
],
[
{
"Name": "Karen Mitchelle",
"email": "k.m.boon#gmail.com",
"password": "$2a$12$PCTK8okWO/ApoNSgXXTIl.oxzwqf.zlHHJaEvxtfxpUrnI1IaGNQC",
"phone": "08128829102",
"role": "Rider",
"status": "Active",
"created_at": "2022-05-17T14:59:22.000Z"
}
]
],
"message": "users list"
}
But I do not want this ^^^ above as a Response. I want something like this instead.
"data":[{
"id": 1,
"fastaUserId": "",
"fullname": "John Qasim",
"email": "j_qasim001#aol.com",
"password": "$2a$12$iAzLsIEcOJpDSSgdUmJBR.e8pWdieUg7N4bFiW0lkgBsQQDA6DwPG",
"state": "Imo",
"role": "Customers",
"city": "Owerri",
"phone_num": "08076631261",
"created_at": "2022-05-17T15:58:26.000Z"
},
{
"id": 1,
"fastaUserId": "",
"fullname": "alex roman",
"email": "alex.roman#juno.com",
"password": "$2a$12$sXpfYaQQIwoBf1KMaPrgT.PioHY4Y6SXD1lpheDB9EPTwfRtsg1p.",
"state": "Lagos",
"city": "city",
"phone_num": "08111111111",
"company_type": "Registered",
"company_name": "Polaris Shipping Inc.",
"company_regnum": "RC-123456",
"c_license": 1,
"role": "Delivery man",
"l_licensenumber": "LAG-2372328",
"company_address": "150 Wole Madariola Close",
"num_employees": "200",
"company_nature": "Sole Propietorship",
"created_at": "2022-05-17T15:57:41.000Z"
},
{
"id": 1,
"fastaUserId": "",
"fullname": "John Legend",
"email": "john.legend#gmail.com",
"password": "$2a$12$KrW0YKsJmvlp2z5uF4V10uLIjcPpSl1ba/LiWuiRpaLs/XRmguXDy",
"phone_num": "0188272610",
"avatar": "test_pic",
"role": "Administrator",
"status": "Active",
"created_at": "2022-05-11T18:48:39.000Z"
},
{
"id": 1,
"Name": "Karen Mitchelle",
"RidersID": "FR-60842",
"Status": "Active",
"email": "k.m.boon#gmail.com",
"password": "$2a$12$PCTK8okWO/ApoNSgXXTIl.oxzwqf.zlHHJaEvxtfxpUrnI1IaGNQC",
"phone": "08128829102",
"No_deliveries": "200",
"rating": "5",
"state": "Lagos",
"city": "Lagos",
"role": "Rider",
"address": "150 Wole Kolawole Str. Lagos Nigeria",
"bike_manufacturer": "Suzuki",
"bike_model": "Suzuki 400",
"bike_year": "2012",
"engine_power": "HP8",
"bike_color": "red",
"license_number": "SMK900-LA",
"license_expiry": "2027-05-01",
"vehicle_id": "LA8373Q2",
"created_at": "2022-05-17T15:59:22.000Z"
}
]
What must i do in my code above to access that data object from results in the response here like this return res.send({ error: false, data: results , message: 'users list' }); and return something like the second Json as shown above? I am trying to get this solved and nothing i have seen on the internet is being quite helpful here. Please i need help

How to parse complex json data in flutter and assign to a model?

This the method I used to fetch the data from an api and then assigning them to a model.
var headers = {
'API-Key': 'TEST_f+y9/tHG+yVxEq3uS3H1ogfezHSCWSq5MsIXUOnIV+Q',
'Content-Type': 'application/json',
};
var data = '"shipment": {
"validate_address": "no_validation",
"ship_to": {
"name": "Amanda Miller",
"phone": "555-555-5555",
"address_line1": "525 S Winchester Blvd",
"city_locality": "San Jose",
"state_province": "CA",
"postal_code": "95128",
"country_code": "US",
"address_residential_indicator": "yes"
},
"ship_from": {
"company_name": "Example Corp.",
"name": "John Doe",
"phone": "111-111-1111",
"address_line1": "4009 Marathon Blvd",
"address_line2": "Suite 300",
"city_locality": "Austin",
"state_province": "TX",
"postal_code": "78756",
"country_code": "US",
"address_residential_indicator": "no"
},
"packages": [
{
"weight": {
"value": 1.0,
"unit": "ounce"
}
}
]
}
}';
final response = await http.post('https://api.shipengine.com/v1/rates', headers: headers, body: data);
if (response.statusCode == 200) {
String responseBody = response.body;
var data = json.decode(responseBody);
print(data);
print(data["rate_response"]["rates"]);
ResRate rates = new ResRate.fromJson(data);
print(rates.rates[0].amount);
} else {
print(response.statusCode);
print(response.body);
}
}
The is model.dart
// Amount amount;
List<Rates> rates;
ResRate({
// this.amount,
this.rates});
factory ResRate.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['rates'] as List;
List<Rates> rates = list.map((i) => Rates.fromJson(i)).toList();
return ResRate(
// amount: Amount.fromJson(parsedJson['amount']),
rates: rates
);
}
}
class Amount{
var currency;
String amount;
Amount({this.currency,
this.amount});
factory Amount.fromJson(Map<String, dynamic> parsedJson){
return Amount(
currency: parsedJson['currency'],
amount : parsedJson['amount'],
);
}
}
class Rates{
var rate_id;
var rate_type;
var carrier_id;
Amount amount;
//List<Amount> shipping_amount;
Rates({
this.rate_id, this.amount,
this.rate_type, this.carrier_id,
});
factory Rates.fromJson(Map<String, dynamic> parsedJson){
// var list = parsedJson['images'] as List;
// List<Image> images = list.map((i) => Image.fromJson(i)).toList();
return Rates(
rate_id: parsedJson['rate_id'],
rate_type: parsedJson['rate_type'],
carrier_id: parsedJson['carrier_id'],
amount: Amount.fromJson(parsedJson['shipping_amount']),
);
}
}
But I'm getting error like this in my console.
Unhandled Exception: NoSuchMethodError: The method 'map' was called on
null
which points toward the model code below
var list = parsedJson['rates'] as List;
List<Rates> rates = list.map((i) => Rates.fromJson(i)).toList();
I tried printing the response body and the response body is fetched successfully and prints in the console.The object rates is also fetched in the response. But appears null .As This response is a complex one , rates too has objects.Here's the response fetched from the api.
"rate_response": {
"rate_request_id": 501834,
"shipment_id": "se-2127183",
"status": "completed",
"created_at": "2019-07-26T22:10:50.286Z",
"rates": [
{
"rate_id": "se-11744390",
"rate_type": "shipment",
"carrier_id": "se-123890",
"shipping_amount": {
"currency": "usd",
"amount": 9.37
},
"insurance_amount": {
"currency": "usd",
"amount": 0.00
},
"confirmation_amount": {
"currency": "usd",
"amount": 0.00
},
"other_amount": {
"currency": "usd",
"amount": 0.00
},
"delivery_days": 3,
"guaranteed_service": false,
"estimated_delivery_date": "2019-07-26T05:00:00.000Z",
"carrier_delivery_days": "Friday by 11:00 PM",
"ship_date": "2019-07-26T05:00:00.000Z",
"negotiated_rate": false,
"service_type": "UPS® Ground",
"service_code": "ups_ground",
"trackable": true,
"validation_status": "valid",
"warning_messages": [],
"error_messages": [],
"carrier_code": "ups",
"carrier_nickname": "UPS-28A1R9",
"carrier_friendly_name": "UPS"
}
],
"invalid_rates": []
},
"shipment_id": "se-2127183",
"carrier_id": "",
"external_shipment_id": null,
"ship_date": "2019-07-26T05:00:00.000Z",
"created_at": "2019-07-26T22:10:50.286Z",
"modified_at": "2019-07-26T22:10:50.286Z",
"shipment_status": "pending",
"ship_to": {
"name": "Amanda Miller",
"phone": "555-555-5555",
"address_line1": "525 S Winchester Blvd",
"city_locality": "San Jose",
"state_province": "CA",
"postal_code": "95128",
"country_code": "US",
"address_residential_indicator": "yes"
},
"ship_from": {
"company_name": "Example Corp.",
"name": "John Doe",
"phone": "111-111-1111",
"address_line1": "4009 Marathon Blvd",
"address_line2": "Suite 300",
"city_locality": "Austin",
"state_province": "TX",
"postal_code": "78756",
"country_code": "US",
"address_residential_indicator": "no"
},
"return_to": {
"company_name": "Example Corp.",
"name": "John Doe",
"phone": "111-111-1111",
"address_line1": "4009 Marathon Blvd",
"address_line2": "Suite 300",
"city_locality": "Austin",
"state_province": "TX",
"postal_code": "78756",
"country_code": "US",
"address_residential_indicator": "no"
},
"confirmation": "none",
"advanced_options": {
"bill_to_account": null,
"bill_to_country_code": null,
"bill_to_party": null,
"bill_to_postal_code": null,
"contains_alcohol": false,
"custom_field1": null,
"custom_field2": null,
"custom_field3": null,
"non_machinable": false,
"saturday_delivery": false
},
"insurance_provider": "none",
"tags": [],
"total_weight": {
"value": 1.00,
"unit": "ounce"
},
"packages": [
{
"weight": {
"value": 1.00,
"unit": "ounce"
},
"dimensions": {
"unit": "inch",
"length": 0.0,
"width": 0.0,
"height": 0.0
},
"insured_value": {
"currency": "usd",
"amount": 0.0
}
}
]
}
I found a fix myself turns out I needed to add the sublist and the object header from the array while mapping in the model.
\\replace this
var list = parsedJson['rates'] as List;
\\with this
var list = parsedJson["rate_response"]['rates'] as List;
List<Rates> rates = list.map((i) => Rates.fromJson(i)).toList();

Fetch and group JSON data for FlatList in React-Native

Here is my Original Json. I'm using fetch and Flatlist for getting and showing json data. My codes works correctly but I want to seperate json by "gender" looks like in below. I researched groupby and reduce functions but i couldn't find solution.
"gender": "male" {
{name,location...},
{name,location...},
{name,location...}
},
"gender": "female" {
{name,location...},
{name,location...},
{name,location...}
}
RN Codes;
export default class Test extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
componentDidMount(){
return fetch('https://randomuser.me/api/?results=5')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.results,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) =>
<View><Text>{item.name.first},{item.gender}</Text></View>
}
keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
If I understand your question correctly, you're wanting to group your data by gender and present the groupings in a list-like component. In that case, the <SectionList> component may be a better fit for this seeing you're introducing extra structure to your dataSource.
To make use of the <SectionList>, first revise your render() function like so:
return (<View style={{flex: 1, paddingTop:20}}>
<SectionList
data={ this.state.dataSource }
renderSectionHeader={
({ section : { gender }}) => (<Text>{ gender }</Text>)
}
renderItem={
({item}) => (<Text>{item.name.first},{item.gender}</Text>)
}
keyExtractor={(item, index) => item.login.uuid + index}
/>
</View>);
The <SectionList> requires dataSource to be organised with a nested data array for each section, so you will need to do the following extra work to transform responseJson.results into a suitable format before updating dataSource on your component state:
componentDidMount(){
return fetch('https://randomuser.me/api/?results=5')
.then((response) => response.json())
.then((responseJson) => {
// Add this to process responseJson.results and pass dataSource result to setState()
const dataSource = responseJson.results.reduce(function(sections, item) {
let section = sections.find(section => section.gender === item.gender);
if(!section) {
section = { gender : item.gender, data : [] };
sections.push(section);
}
section.data.push(item);
return sections;
}, []);
this.setState({
isLoading: false,
dataSource: dataSource // Pass the dataSource that we've processed above
});
})
.catch((error) =>{
console.error(error);
});
Finally, you'll want to update your initial state in the component constructor to ensure that render() can complete while the fetch() request is busy, by adding this:
constructor(props){
super(props);
this.state ={
isLoading: true,
dataSource: [] // Add this
}
}
Here's a working code snippet to show how your JSON data is processed to group it by the gender key - hope this helps!
var responseJson = {
"results": [
{
"gender": "female",
"name": {},
"location": {},
"email": "karla.ferreira#example.com",
"login": {
"uuid": "86f5b29b-1f36-4082-8b88-18df6c5985f9",
"username": "orangebutterfly557",
"password": "kojak",
"salt": "7mybIlaS",
"md5": "c85980c5ce76b38b71d162402d71eb1c",
"sha1": "e38b87aaf2d5be040ed0741faea0e4b97d52fd35",
"sha256": "9f44b3da697a63b4d5c393513ab651e8fe0315d1ee199d5bd03797279189c881"
},
"dob": {
"date": "1990-07-01T17:43:24Z",
"age": 28
},
"registered": {
"date": "2018-05-17T15:57:05Z",
"age": 0
},
"phone": "(73) 6539-5154",
"cell": "(52) 4127-1768",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/41.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/41.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/41.jpg"
},
"nat": "BR"
},
{
"gender": "female",
"name": {
"title": "ms",
"first": "isabel",
"last": "caballero"
},
"location": {
"street": "7168 calle de bravo murillo",
"city": "valladolid",
"state": "canarias",
"postcode": 79290,
"coordinates": {
"latitude": "-69.7045",
"longitude": "4.0689"
},
"timezone": {
"offset": "-9:00",
"description": "Alaska"
}
},
"email": "isabel.caballero#example.com",
"login": {
"uuid": "794613c2-cac6-4c71-a2b6-f2ce119b46d2",
"username": "beautifulbutterfly648",
"password": "beer",
"salt": "5fhMSsyZ",
"md5": "ee62bb75d8f0a95d1d0788fff592e6dc",
"sha1": "71aa4f04cba4a601a52e358b1986a627edecab5a",
"sha256": "b5c3c0b607f15454f0faa8d7f68fc0fa981b9b3283fc9f37cf0ecf2a0f608c8d"
},
"dob": {
"date": "1951-03-16T06:28:07Z",
"age": 67
},
"registered": {
"date": "2008-08-12T17:02:44Z",
"age": 10
},
"phone": "938-596-606",
"cell": "604-802-919",
"id": {
"name": "DNI",
"value": "08944217-Q"
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/18.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/18.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/18.jpg"
},
"nat": "ES"
},
{
"gender": "male",
"name": {
"title": "mr",
"first": "owen",
"last": "ouellet"
},
"location": {
"street": "8868 frederick ave",
"city": "waterloo",
"state": "newfoundland and labrador",
"postcode": "J9T 1I9",
"coordinates": {
"latitude": "-74.7042",
"longitude": "-147.1181"
},
"timezone": {
"offset": "-3:30",
"description": "Newfoundland"
}
},
"email": "owen.ouellet#example.com",
"login": {
"uuid": "91634e9f-9a0b-406d-83f1-f0df7731c922",
"username": "beautifulleopard930",
"password": "valkyrie",
"salt": "OEfVANKW",
"md5": "bda8ccb4284727538bd24994ee1a91ef",
"sha1": "f193f9836421fa287f01e8f8305140b0d2d87596",
"sha256": "28a0197375cdfc8d22ec0e388ef93f18705dcb909d6944719f217d60ac45cd24"
},
"dob": {
"date": "1978-04-05T03:58:10Z",
"age": 40
},
"registered": {
"date": "2008-09-04T08:08:37Z",
"age": 10
},
"phone": "527-612-8558",
"cell": "573-419-2272",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/60.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/60.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/60.jpg"
},
"nat": "CA"
},
{
"gender": "female",
"name": {
"title": "mrs",
"first": "lily",
"last": "campbell"
},
"location": {
"street": "6239 dalhousie ave",
"city": "brockton",
"state": "northwest territories",
"postcode": "X6R 5W4",
"coordinates": {
"latitude": "44.3179",
"longitude": "77.2683"
},
"timezone": {
"offset": "+3:30",
"description": "Tehran"
}
},
"email": "lily.campbell#example.com",
"login": {
"uuid": "5e7f5ca7-1c6a-49cf-98ea-6993ba13e98d",
"username": "sadleopard720",
"password": "noodles",
"salt": "dO6LaBuZ",
"md5": "3b946373260729b1c598fc76b953b0f7",
"sha1": "9df4c90b67eb00fb5f46b291d006333418b837cb",
"sha256": "05bc6bc7749a7483e45afcd2cf13a44642253d69ad2164e7315d04ae12a54178"
},
"dob": {
"date": "1995-10-01T19:06:38Z",
"age": 23
},
"registered": {
"date": "2013-10-20T00:40:17Z",
"age": 5
},
"phone": "474-554-3856",
"cell": "280-264-4427",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/9.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/9.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/9.jpg"
},
"nat": "CA"
},
{
"gender": "male",
"name": {
"title": "mr",
"first": "matias",
"last": "salo"
},
"location": {
"street": "1152 itsenäisyydenkatu",
"city": "lieksa",
"state": "northern ostrobothnia",
"postcode": 89650,
"coordinates": {
"latitude": "15.4636",
"longitude": "84.5787"
},
"timezone": {
"offset": "+11:00",
"description": "Magadan, Solomon Islands, New Caledonia"
}
},
"email": "matias.salo#example.com",
"login": {
"uuid": "562f43c4-5fc1-45f2-bb27-99516a0ae907",
"username": "sadcat151",
"password": "aaaaaaaa",
"salt": "CpmHRSKk",
"md5": "ea3078f64987b8c1d6e697d871a3239e",
"sha1": "bdd64c7d8bb3383a3ac24b6716214385972127be",
"sha256": "5ccfa3847e4c0a7878dd35ccbcabcc7b411f8b95f15d222100edc8cd79cabbd4"
},
"dob": {
"date": "1964-02-17T18:40:47Z",
"age": 54
},
"registered": {
"date": "2004-12-03T13:58:39Z",
"age": 14
},
"phone": "08-963-701",
"cell": "047-041-00-91",
"id": {
"name": "HETU",
"value": "NaNNA305undefined"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/60.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/60.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/60.jpg"
},
"nat": "FI"
}
],
"info": {
"seed": "21ef5612af5cb358",
"results": 5,
"page": 1,
"version": "1.2"
}
};
const result = responseJson.results.reduce(function(sections, item) {
let section = sections.find(section => section.gender === item.gender);
if(!section) {
section = { gender : item.gender, data : [] };
sections.push(section);
}
section.data.push(item);
return sections;
}, []);
console.log(result);
.as-console-wrapper {
height:100% !important;
max-height:unset !important;
}

angularJS JSON parsing

I am new to angularJS and trying to parse the data and display it on a page.
{
"count": 13,
"status": 200,
"statusMessage": "OK",
"userContact": [
{
"user": {
"id": 1,
"firstName": "test",
"lastName": "test",
"universityId": 1,
"email": "test#harbingergroup.com",
"password": "",
"phoneNo": "1234567890",
"gender": "M",
"userType": 1,
"medicalComments": "",
"dob": "2015-02-22",
"universityAffiliation": 1,
"cityId": "1"
},
"userContactList": {
"count": 2,
"status": 200,
"statusMessage": "OK",
"contact": [
{
"id": 2,
"userId": 1,
"firstName": "test",
"lastName": "user",
"phoneNo": "9876543210",
"email": "test#example.com"
},
{
"id": 24,
"userId": 1,
"firstName": "first1",
"lastName": "last1",
"phoneNo": "9876543210",
"email": "test#example.com"
}
]
}
}]
}
this is my JSON data.What i am trying is :
<tr ng-repeat="studentDetails in studentProfileData">
studentDetails.status for getting status and studentDetails.userContacts.firstName for first name
but I am not getting the data. What is wrong here?
Assuming that studentProfileData contains a list of users (userContact):
studentDetails.user.firstName
will contain "test"