How to remove 'data' array key in Json response - json

I'm new in Laravel 7 and now my problem is the JSON response data wrapped by the data array key.
Response data
{
"data": [
{
"id": 3017,
"total": "87.98",
"subtotal": 83,
"total_tax_items": 4.98,
"count_items": 3,
}
]
}
Expected response data
{
{
"id": 3017,
"total": "87.98",
"subtotal": 83,
"total_tax_items": 4.98,
"count_items": 3,
}
}
Here is my code that returns from the eloquent collection.
$query = Sale::with(['items'])
->select('id', 'total')
->get();
return json_resp($query);

try return as:
return response()->json($result);

Related

Filter to retrieve specific value in nested object using Vue

I have a nested json object:
{
"51": {
"wheels": 10,
"id": 1,
"name": "truck"
},
"55": {
"wheels": 4,
"id": 33,
"name": "Car"
},
"88": {
"wheels": 2,
"id": 90,
"name": "Bike"
}
}
I would like to filter by ID but only return the wheels so ie.
Filter ID = 33 which would return 4.
I have tried using the .filter function but I get an error: filter is not a function which I assume is because this is not an array. I have tried to replicate using answer here:
How to filter deeply nested json by multiple attributes with vue/javascript
Without success because the json has a key (51, 55, 88) so I am stumped.
Thanks for the help in advance.
You can use Object.values to convert the object into an array and then use find method on it to retrieve the specific object. Something like:
Object.values(obj).find(val => val.id === 33)?.wheels
let obj = {
"51": {
"wheels": 10,
"id": 1,
"name": "truck"
},
"55": {
"wheels": 4,
"id": 33,
"name": "Car"
},
"88": {
"wheels": 2,
"id": 90,
"name": "Bike"
}
}
console.log(Object.values(obj).find(val => val.id === 33)?.wheels)

How to remove brakets on Json respone

im working on Laravel Rest Api with passeport ,
in return response()->json() i want to trim the brackets
I've tried trim($json,'[]') function but it's not what i want
public function getOffers()
{
$offers = Offer::where('type', 'primary')->where('active', 1)->get();
$paks = Offer::where('type', 'pack')->where('active', 1)->get();
return response()->json([
'offersList' => $offers,
'packsList' => $paks,
], 200);
}
i expect the output will be
{
"offersList": {
{
"id": 3,
"name": "Gold",
"description": null
}
},
"packsList":[]
}
but the actual result is
{
"offersList": [
{
"id": 3,
"name": "Gold",
"description": null
}
],
"packsList":[]
}
$offers is a collection, and thus an array in JSON.
If $offers should be a single item, use first() instead of get() and it will be rendered as a single object in your JSON instead of an array of objects.
$offers = Offer::where('type', 'primary')->where('active', 1)->first();
If $offers should, at times, contain multiple offers, leave it as-is; it's correct!
Braces {} nested in another object is not valid JSON.
Objects can be used in property values and as array elements.
Not valid JSON
{
"offersList": {
{
"id": 3,
"name": "Gold",
"description": null
}
}
}
Valid option 1
{
"offersList": [
{
"id": 3,
"name": "Gold",
"description": null
}
]
}
Valid option 2
{
"offersList": {
"id": 3,
"name": "Gold",
"description": null
}
}
You can use online linters to quickly validate your JSON structure.
https://jsonformatter.curiousconcept.com/

Typescript - Angular http post

I am building an autocomplete functionality.
1) The backend RESTful service returns following response for partially entered keyword.
JSON response
{
"suggest": {
"resultsuggest": [
{
"text": "Ke",
"offset": 0,
"length": 2,
"options": [
{
"text": "Kevin Johnson",
"_index": "customernames",
"_type": "_doc",
"_id": "1",
"_score": 3
}]
}
]
}
}
2) In Angular application, what should I do to extract the options array from the JSON response and return it back for this fetch function??
Note - I want to use the Promise instead of Observable.
fetch(params?: HttpParams): Promise<any> {
const query = params.get('query');
const headers = new HttpHeaders().set("Content-Type", "application/json");
let postData = "{ \"_source\": \"suggest\", \"suggest\": {\"resultsuggest\" : { \"prefix\" : \""+query+"\",\"completion\" : { \"field\" : \"suggest\", \"size\" : 5 }}}}";
return this._http.post<any[]>('http://127.0.0.1:9200/customernames/_search?pretty',postData, {headers})
.pipe(map(result=> {
// what should I do to extract the Options array from the JSON response and return it back in this fetch function??
return ????;
}),
delay(400)
).toPromise();
}
Appreciate your help!
thanks!
Updated:
1) JSON response is fixed.
2) changed return this._http.post<any> to return this._http.post<any[]>
As Arcteezy suggested, the following worked
map(result=> { return result.suggest.resultsuggest[0].options; }

How to add custom properties to Laravel paginate json response

I have the following simple index method:
public function index()
{
// dd(Poll::paginate(2));
return response()->json(Poll::paginate(2),200);
}
The output of that method is looks like the following json object:
{
"current_page": 1,
"data": [
{
"id": 1,
"title": "I suppose?' said Alice. 'Why, you don't know.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
},
{
"id": 2,
"title": "Alice; but she knew that it seemed quite.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
}
],
"first_page_url": "http://127.0.0.1:8000/polls?page=1",
"from": 1,
"last_page": 6,
"last_page_url": "http://127.0.0.1:8000/polls?page=6",
"next_page_url": "http://127.0.0.1:8000/polls?page=2",
"path": "http://127.0.0.1:8000/polls",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 11
}
I want to add another array property after "total: 11" attribute such as:
,
"anotherData" : [
"userId": 1,
"userName": "john10",
"message": "This is a message"
]
I have tried to understand how response()->json() works, so it can extract some data from LengthAwarePaginator object which it is the output of Poll::paginate(2) from this resource, but I could not able to understand how does it able to get an array from LengthAwarePaginator that holds the resultant keys in the json object?!
From the regarded resource above, the json() method takes an array and, I guess that, if the parameter is not an array, it tries to convert it to array, specially if it is an object like LengthAwarePaginator, so it may use toArray() method.
I have tried replacing return response()->json(Poll::paginate(2),200) with return response()->json(Poll::paginate(2)->toArray,200), then I have got the same output. Hence, I have decided to replace the code of my index method to be like the following:
public function index()
{
//dd(Poll::paginate(2)->toArray());
$output = Poll::paginate(2)->toArray();
$output['userData'] = ['userId' => \Auth::user()->id, 'userEmail' => \Auth::user()->email];
return response()->json($output,200);
}
The resultant output is:
...
"path": "http://127.0.0.1:8000/polls",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 11,
"userData": {
"userId": 1,
"userEmail": "lion#example.com"
}
}
If you're directly responding with the paginated data, a better option would be to wrap it in a Resource Collection and adding meta data to it.
This is how I implemented it.
CategoryController.php
public function index()
{
return new CategoryCollection(Category::paginate(10));
}
CategoryCollection.php
public function toArray($request)
{
return [
'status' => 1,
'message' => 'Success',
'data' => $this->collection,
];
}
Since Collection extends JsonResource, your response would automatically be converted to JSON when returned from the Controller.

Want to remove Unexpected object like "headers","original","exception" from Laravel JSON output

I am getting JSON response like this. But I want to remove "headers", "original" and "exception".
{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}
Output expected:
{
"data": {
"id": 271,
"name": "TestController",
"parent_id": null
},
"errors": [],
"success": true,
"status_code": 200
}
You are returning a response()->json() inside another response()->json() something along the way:
response()->json(response()->json($data,200),200)
or more like:
$data = [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
];
$response = response()->json($data,200);
return response()->json($response ,200);
You may not have notice it because of a function returning the first response()->json() into the second one
You can use this
$json='{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}';
$arr=json_decode($json);
$data=$arr->original[0];
$new_json=array();
$new_json['data']=$data;
$new_json['errors']=[];
$new_json['success']=true;
$new_json['status_code']=200;
$new_json=json_encode($new_json);
You may have doubled the data json return with response()->json()
you can use array only
return ["data"=> [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
],
"errors"=> [],
"success"=> true,
"status_code"=> 200
];
In my case this problem solved with this solution:
You can use:
return json_decode(json_encode($ResponseData), true);
And return response
This is what I did, and it worked for me:
just call the original object after getting your response like this:
public function user_object(){
return $this->me()->original;
}
This is the me() function that returns user details
public function me()
{
return response()->json(auth('users')->user()->only(['id','name','email','status','phonenumber','type']));
}
This is my response from post man:
{
"success": true,
"user": {
"id": 29,
"name": "test6",
"email": "test6#gmail.com",
"status": 1,
"phonenumber": "413678675",
"type": "user"
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9hdXRoXC9yZWdpc3RlciIsImlhdCI6MTU5OTQ3MDc3OCwiZXhwIjoxNTk5NDc0Mzc4LCJuYmYiOjE1OTk0NzA3NzgsImp0aSI6InFyUWEyTVNLVzR4a2o0ZVgiLCJzdWIiOjI5LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.SMHgYkz4B4BSn-fvUqJGfsgqHc_r0kMDqK1-y9-wLZI",
"expires_in": 3600
}
The issue is triggered because you are returning nested responses somewhere in your code.
Here is a simple code that demonstrates the issue and the fix.
// A normal function that you think it returns an array
// but instead, it is returning a response object!
public function get_data(){
//ISSUE
return response([1, 2, 3]); // <- this will trigger the issue becuase
// it returns the data as a response not an array
//FIX
return [1, 2, 3]; // <- this will work as intended
// bacause the data is returned as a normal array
}
public function get_all_data(){
$first_array = [1, 2];
$second_array = [2, 3];
$third_array = get_data(); // <- here is the call to the function
// that should return an array
//Return the JSON response
return response([first_array, second_array, third_array]);
}