Flutter : display data from json - json

i have a json data, i want to display it in my flutter app ,so how can i display data from [bookings] partie,for now its easy i use this data[0]['now']['location'], but i have a difficulty to find a way to display data from booking. can someone help me plz
[
{
"now":{
"id": 28,
"userId": 6,
"bookingTypeId": 2,
"carWasherId": 26,
"buildingId": 4,
"serviceId": 1,
"packageId": 1,
"vehiculeId": 7,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-18 12:30:00",
"date": "2021-12-18",
"address": null,
"longitude": -6.7436544,
"latitude": 33.9968,
"rate": null,
"created_at": "2021-10-29T14:26:16.000000Z",
"updated_at": "2021-11-10T15:02:33.000000Z",
"location": "",
"duration": 30,
"start": "12:30",
"end": "13:00"
}
},
[
"bookings",
[
{
"id": 29,
"userId": 6,
"bookingTypeId": 1,
"carWasherId": 26,
"buildingId": 2,
"serviceId": 1,
"packageId": null,
"vehiculeId": 2,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-18 09:47:33",
"date": "2021-12-18",
"address": null,
"longitude": null,
"latitude": null,
"rate": null,
"created_at": "2021-10-29T15:03:14.000000Z",
"updated_at": "2021-11-10T15:00:25.000000Z",
"location": "",
"duration": 20,
"start": "09:47",
"end": "10:07"
},
{
"id": 30,
"userId": 6,
"bookingTypeId": 2,
"carWasherId": 26,
"buildingId": 3,
"serviceId": 1,
"packageId": 1,
"vehiculeId": 7,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-22 21:30:00",
"date": "2021-12-22",
"address": null,
"longitude": -6.7436544,
"latitude": 33.9968,
"rate": null,
"created_at": "2021-10-29T15:18:45.000000Z",
"updated_at": "2021-11-10T22:16:47.000000Z",
"location": "",
"duration": 25,
"start": "21:30",
"end": "21:55"
}
]
]
]

Create a named constructor fromJson which accepts your json data and returns a list of Books (see here: https://docs.flutter.dev/development/data-and-backend/json)
class Book{
final String name;
final String id;
User(this.name, this.id);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
id= json['id'];
Map<String, dynamic> toJson() => {
'name': name,
'id': id,
};
}

First, you create a model of your object. and create JSON file and put it in your project.
String productData = await DefaultAssetBundle.of(context).loadString("assets/product.json");
final jsonResult = jsonDecode(productData);
You can get hear your JSON data and after that, you can initialise your JSON data to the model. like this
var objProductDetails = ProductDetailsDataModel.fromJson(jsonResult);

Related

Pagination not working while retriving data with costom json function

I'm fetching data to paginate but pagination is not working, the fetch response is added below, if I return the query relation it retrieves correct data but when I pass it to the custom response function it fetch data only but not the pagination links
try {
$type = 'success';
$status_code = 200;
$message = 'Posts data listed.';
$response = PostResource::collection(Post::with(['associate:id,name,avatar', 'comments:id,commenter_id,commentable_id,comment,created_at'])
->latest('posts.created_at')
->paginate(2));
} catch (Exception $e) {
$type = 'error';
$status_code = $e->getCode();
$message = $e->getMessage();
$response = false;
}
return response_data($type, $status_code, $message, $response);
Here is my response_data function code
function response_data($type, $status, $message = false, $response)
{
return response()->json(['type' => $type, 'status' => $status, 'message' => $message, 'response' => $response]);
}
but if return the query directly it retrieves data with pagination
here is my response that retrieved by the collection
{
"type": "success",
"status": 200,
"message": "Posts data listed.",
"response": [
{
"id": 32,
"associate_id": 5,
"title": "Test Title",
"content": "Post descriptuoin",
"image": "https://oppazz.oppazzgiftcode.com/images/posts/1632472717.Laravel.png",
"created_at": "2 months ago",
"associate": {
"name": "Code Logic Technologies Pvt. Ltd.",
"avatar": "https://oppazz.oppazzgiftcode.com/images/associates/1633002782_logo.png"
},
"comments": [
{
"id": 13,
"commenter_id": "62",
"commentable_id": "32",
"comment": "Nice offer",
"created_at": "2 months ago",
"user": {
"id": 62,
"name": "Rikesh Shakya",
"username": "rikesh-shakya",
"mobile_number": "9823783191",
"email": "skybks5#gmail.com",
"provider_id": null,
"avatar": "https://oppazz.oppazzgiftcode.com/images/logo.png",
"email_verified_at": null,
"status": "Y",
"created_at": "2021-06-11T18:05:07.000000Z",
"updated_at": "2021-06-11T18:05:07.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
},
{
"id": 16,
"commenter_id": "88",
"commentable_id": "32",
"comment": "tetetete",
"created_at": "2 months ago",
"user": {
"id": 88,
"name": "Neelam Kera",
"username": "neelam-ranjitkar",
"mobile_number": "9860322060",
"email": "shresthaneelam19#gmail.com",
"provider_id": null,
"avatar": "https://oppazz.oppazzgiftcode.com/images/logo.png",
"email_verified_at": null,
"status": "Y",
"created_at": "2021-07-15T14:08:21.000000Z",
"updated_at": "2021-07-15T14:08:21.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
}
],
"associate_social_sites": {
"id": 5,
"associate_id": 5,
"facebook": "https://www.fachook.com",
"instagram": "https://www.instagram.com",
"twitter": "https://www.twitter.com",
"status": "Y",
"created_at": null,
"updated_at": "2021-09-24T09:29:57.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
},
{
"id": 31,
"associate_id": 9,
"title": "OppazZ Coffee For Happiness (Giveaway series)",
"content": "OppazZ",
"image": "https://oppazz.oppazzgiftcode.com/images/posts/1632367205.kamloops-art-page-2.jpg",
"created_at": "2 months ago",
"associate": {
"name": "OppazZ",
"avatar": "https://oppazz.oppazzgiftcode.com/images/associates/1622551849_184399208_2242958835839866_1824735327179728878_n.jpg"
},
"comments": [],
"associate_social_sites": null
}
]
}
how can it be resolved and fetch pagination link along with the data fetched above
The Laravel paginator result classes implement the Illuminate\Contracts\Support\Jsonable interface contract and expose the toJson method, so it's very easy to convert your pagination results to JSON.
You may also convert a paginator instance to JSON by simply returning it from a route or controller action:
https://laravel.com/docs/5.3/pagination#converting-results-to-json

vue.js - how to create a nested arrays

i want to calculate the total costs of products selected by a user under each company.There is my code.
let companiesProductPrices = [];
let prices = [];
this.selectedCompaniesDetails.forEach(company => {
this.chosenItems.forEach(item=> {
item.product_attributes.forEach(product => {
if(company.id == product.company_id)
{
prices.push(product.price);
companiesProductPrices[company.id] = prices;
}
})
});
})
Background information. I have to objects. The products object and the companies object.
Products object referred to as this.chosenItems in my code and is like this;
[
{
"id": 1,
"name": "Zimgold",
"slug": null,
"product_category_id": 1,
"industry_id": 1,
"category": {
"id": 1,
"name": "Cooking Oil",
"slug": null,
"industry_id": 1
},
"product_attributes": [
{
"id": 1,
"description": "2 litres",
"discount": null,
"price": "120",
"tax": null,
"company_id": 1,
"product_id": 1
},
{
"id": 5,
"description": "2 litres",
"discount": null,
"price": "130",
"tax": null,
"company_id": 2,
"product_id": 1
}
]
},
{
"id": 4,
"name": "Silo",
"slug": null,
"product_category_id": 3,
"industry_id": 1,
"category": {
"id": 3,
"name": "Mealie Meal",
"slug": null,
"industry_id": 1
},
"product_attributes": [
{
"id": 4,
"description": "10 kgs",
"discount": null,
"price": "130",
"tax": null,
"company_id": 1,
"product_id": 4
}
]
}
]
and my company object referred to as this.selectedCompaniesDetails in my code and is like this.
[
{
"id": 1,
"name": "Spar",
"slug": null,
"industry_id": 1
},
{
"id": 2,
"name": "Ok",
"slug": null,
"industry_id": 1
},
{
"id": 3,
"name": "TM",
"slug": null,
"industry_id": 1
},
{
"id": 4,
"name": "choppies",
"slug": null,
"industry_id": 1
},
{
"id": 5,
"name": "Bon Marche",
"slug": null,
"industry_id": 1
}
]
I'm wishing to get the totals of all products that are belong to each company. Let me show you my UI.
So what i want is under spar the total should be 250 and under 130 and so forth for all other companies. Thank you in advance
This is one of many solutions. It's improvable, it's just to show you the way.
#1 Create an object where key is company id and value is the array of prices for that company
const priceByCompany = products.reduce((tot, prod) => {
prod.product_attributes.forEach((p) => {
if (!tot[p.company_id]) {
tot[p.company_id] = []
}
const numberPrice = parseInt(p.price, 10)
tot[p.company_id].push(numberPrice)
})
return tot
}, {})
// { 1: [120, 130], 2: [130] }
#2 Reduce all value array to sum them up.
Object.keys(priceByCompany).forEach((company) => {
const total = priceByCompany[company].reduce((tot, price) => tot + price, 0)
priceByCompany[company] = total
})
// { 1: 250, 2: 130 }
See the code in action: Jsfiddle

laravel api : nested comment and replies

I'm a laravel beginner and want to build an API with laravel 8.
I have a nested comment and replies system for my posts
and the relation between comments and posts are polymorphic
i want to show a post and comments and replies as JSON
but i don't know my query is correct or not , because i can't understand relation between comments and replies and i just can see all comments and replies related to the post.
this is the JSON response in postman :
[
{
"id": 45,
"category_id": 11,
"user_id": 1,
"title": "title example",
"body": "body example",
"video": null,
"study_time": "8",
"likes": null,
"status": null,
"tags": [],
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:09:14.000000Z",
"updated_at": "2021-05-01T14:09:14.000000Z",
"comments": [
{
"id": 13,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": null,
"name": "sara",
"email": "sara#gmail",
"comment": "its good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:14.000000Z",
"updated_at": "2021-05-01T14:10:14.000000Z"
},
{
"id": 14,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 13,
"name": "john",
"email": "john#gmail.com",
"comment": "its not good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:50.000000Z",
"updated_at": "2021-05-01T14:10:50.000000Z"
},
{
"id": 15,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 14,
"name": "sara",
"email": "sara#gmail.com",
"comment": "why?",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:11:12.000000Z",
"updated_at": "2021-05-01T14:11:12.000000Z"
}
],
}
]
as you see , the replies aren't in array and it's not clear which is a replay and which is a comment
so this is my PostDetailsController :
class PostDetailsController extends Controller
{
/**
* Disply post and comments with replies
**/
public function showPost($id){
$postFind = Post::find($id);
if(is_null($postFind)){
return response()->json('not found' , 404);
}
$post = Post::with('comments')->find($id);
return response()->json([$post] , 200);
}
about comments :
comments table :
chema::create('comments', function (Blueprint $table) {
$table->id();
$table->integer('commentable_id');
$table->string('commentable_type');
$table->unsignedBigInteger('parent_id')->nullable(); //nullable for comments , with value for replies
$table->string('name' , 45);
$table->string('email');
$table->longText('comment');
$table->foreign('parent_id')->references('id')->on('comments')->onUpdate('cascade')->onDelete('cascade');
$table->rememberToken();
$table->softDeletes();
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
so if parent_id is NULL it's a comment and if has values ( id of parent comments ) it's a reply. (and reply of reply has previous reply id as parent_id )
and the models :
Post :
class Post extends Model
{
protected $fillable = [
'user_id' ,
'category_id' ,
'title' ,
'body' ,
'study_time',
'status',
'tags',
];
public function comments()
{
return $this->morphMany(Comment::class, 'commentable' );
}
}
Comment :
class Comment extends Model
{
protected $fillable = [
'parent_id' , 'name' , 'email' , 'comment' , 'status' , 'images'
];
use HasFactory;
public function commentable(){
return $this->morphTo();
}
public function replies()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
so can you please tell me is my query wrong?
and what should i do for show replies in an array ?
EDIT
i changed my code to this :
class PostDetailsController extends Controller
{
/**
* Disply post and comments with replies
**/
public function showPost($id){
$postFind = Post::find($id);
if(is_null($postFind)){
return response()->json('not found' , 404);
}
$post = Post::with('comments.replies')->find($id);
return response()->json([$post] , 200);
}
and the response is :
[
{
"id": 45,
"category_id": 11,
"user_id": 1,
"title": "title example",
"body": "body example",
"video": null,
"study_time": "8",
"likes": null,
"status": null,
"tags": [],
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:09:14.000000Z",
"updated_at": "2021-05-01T14:09:14.000000Z",
"comments": [
{
"id": 13,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": null,
"name": "sara",
"email": "sara#gmail",
"comment": "its good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:14.000000Z",
"updated_at": "2021-05-01T14:10:14.000000Z",
"replies": [
{
"id": 14,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 13,
"name": "john",
"email": "john#gmail.com",
"comment": "its not good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:50.000000Z",
"updated_at": "2021-05-01T14:10:50.000000Z"
}
]
},
{
"id": 14,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 13,
"name": "john",
"email": "john#gmail.com",
"comment": "its not good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:50.000000Z",
"updated_at": "2021-05-01T14:10:50.000000Z",
"replies": [
{
"id": 15,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 14,
"name": "sara",
"email": "sara#gmail.com",
"comment": "why?",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:11:12.000000Z",
"updated_at": "2021-05-01T14:11:12.000000Z"
}
]
},
{
"id": 15,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 14,
"name": "sara",
"email": "sara#gmail.com",
"comment": "why?",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:11:12.000000Z",
"updated_at": "2021-05-01T14:11:12.000000Z",
"replies": []
}
],
}
]
so i can see the replies of every comment or reply in the response , but as you see the replies are repeated and the last reply that has no reply ,has "replies[]"
What should I do to not show the replay again?
So a couple things here that you could do, firstly your replies have the commentable_type and commentable_id whereas these should probably be nullable since when looking at replies you only really need to know its parent and not the post as you can get this through the parent.
This then allows your $post->comments relationship to not return replies to comments.
Next you can use dot notation to add replies to your comments.
$post = Post::with('comments.replies')->find($id);
This would then return something like this
[
{
"id": 1,
"title": "Title",
"body": "Body",
"created_at": "2021-05-01T11:34:27.000000Z",
"updated_at": "2021-05-01T11:34:28.000000Z",
"comments": [
{
"id": 1,
"post_id": 1,
"parent_id": null,
"body": "No Replies",
"created_at": "2021-05-01T11:34:41.000000Z",
"updated_at": "2021-05-01T11:34:43.000000Z",
"replies": []
},
{
"id": 2,
"post_id": 1,
"parent_id": null,
"body": "One Reply",
"created_at": "2021-05-01T11:35:18.000000Z",
"updated_at": "2021-05-01T11:35:19.000000Z",
"replies": [
{
"id": 3,
"post_id": null,
"parent_id": 2,
"body": "Reply",
"created_at": "2021-05-01T11:35:29.000000Z",
"updated_at": "2021-05-01T11:35:32.000000Z"
}
]
}
]
}
]

Python 3 - Extracting value from key in nested dictionary

Hoping for some pointers here as I'm striking out with my attempts. Am working with python 3.8.5.
I'm querying a Car Park booking system that returns a json list of availability. The result has lots of nested dictionaries and I'm struggling to extract just the values i want.
This is what I've been doing:
import requests
import json
enquiry = requests.post(url.....) #queries api, this works fine
results = enquiry.text #extracts response data
dictionary = json.loads(results) #convert response to python dict
If there is one slot available, I get this output (apologies for length). If there are multiple slots available, i get the same output repeated:
{
"data": {
"services": [{
"id": null,
"name": null,
"services": [{
"id": null,
"name": "Car Park",
"met": true,
"filterCount": 1,
"primary": true,
"options": [{
"id": "9",
"images": [],
"available": true,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": null,
"startDate": "2020-08-18T13:30:00Z", <--this is what I want to extract
"endDate": "2020-08-18T14:30:00Z",
"geo": {
"lat": 0.0,
"lng": 0.0
},
"selected": false,
"linkedServices": [],
"tiers": null
}]
}],
"currentBookingId": null,
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
},
"endDate": {
"ms": 1597761000000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 15,
"days": 0
}
},
"sessionId": "2222222",
"chargeType": 1,
"hasPrimaryBookable": false,
"hasBookable": false,
"hasDiscounts": false,
"hasMultipleTiers": false,
"isPreferred": false,
"primaryServiceAvailable": true,
"primaryServiceId": null,
"primaryServiceType": "undefined",
"unavailableAttendees": []
}],
"bookingLimit": null
},
"success": true,
"suppress": false,
"version": "2.3.293",
"message": null,
"result": null,
"errors": null,
"code": null,
"flags": 0,
"redirect": null
}
I want to extract:
"startDate": "2020-08-18T13:30:00Z"
from each key, value pair in any of the returned slots. However, I cant work it out.
Extracting the whole of this nested dictionary would also contain the same data, but would then involve more work to tidy it up after.
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
I've tried loads of dictionary.get and dictionary.items variations, but cant seem to get anywhere.
I tried something like
key = ('startDate')
availability = dictionary.get(key)
print(availability)
this just returns 'none', so think im way off
Any pointers?
Thanks in advance!
Thanks for the full data. It makes testing easier :)
I had to replace null -> None, true -> True, false -> False
slot = {
"data": {
"services": [{
"id": None,
"name": None,
"services": [{
"id": None,
"name": "Car Park",
"met": True,
"filterCount": 1,
"primary": True,
"options": [{
"id": "9",
"images": [],
"available": True,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": None,
"startDate": "2020-08-18T13:30:00Z", # <--this is what I want to extract
................
print("Start Date:", slot['data']['services'][0]['services'][0]['options'][0]['startDate'])
Output
Start Date: 2020-08-18T13:30:00Z

How do i check if certain value is a string using Postman

I am trying to access a values inside keys using Postman and test what type of value it. The format i receive is Json and it is an array of few Json objects with the same Key and i am trying to test if the value matches the format ( for example if the value of a key is a string or int or...)
[
{
"id": 1,
"accountNo": "1234567891234567",
"companyCode": "Test",
"apiKey": null,
"name": "Test",
"channel": "SFTP",
"levelOne": 1,
"levelTwo": 1,
"levelThree": 1,
"templateName": null,
"codeFormat": "testni",
"isAmountChangeAllowed": true,
"isActive": false,
"phoneNumber": "123456789",
"email": "test#test.com",
"pdfFileUrl": "/app/",
"interval": 0,
"day": 0
},
{
"id": 4,
"accountNo": "54345",
"companyCode": "TEST",
"apiKey": null,
"name": "Testno Name",
"channel": "SFTP",
"levelOne": 1,
"levelTwo": 1,
"levelThree": 1,
"templateName": null,
"codeFormat": "testno",
"isAmountChangeAllowed": true,
"isActive": true,
"phoneNumber": "312",
"email": "test#test.com",
"pdfFileUrl": "/app/op",
"interval": 2,
"day": 5
},
Error message i get is "AssertionError: expected undefined to deeply equal 5"