Return JSON data with predefined key Yii2 - json

I use Yii2 and I created RESTful API service. But in my app I want to return JSON data with predefined key for all responses. For example:
Default respons:
[
{
"id": 1,
"title": "Brooklyn"
},
{
"id": 2,
"title": "Financial District"
},
{
"id": 4,
"title": "Social District"
}
]
But I want to get smth like that:
"data": [
{
"id": 1,
"title": "Brooklyn"
},
{
"id": 2,
"title": "Financial District"
},
{
"id": 4,
"title": "Social District"
}
]

You should simply customize rest serializer, in your controller :
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'data',
];
Read more.

Related

Convert two dimentional array into the json object in Laravel

I am converting a two-dimensional array into a JSON object.
Now my controller returning this output:
[
[
{
"id": 1,
"title": "V1",
"project_id": 1
}
],
[]
]
Want to convert it like:
[
{
"id": 1,
"name": "Laravel"
},
{
"id": 2,
"name": "Wordpress"
}
]
My controller code:
$user = auth()->user();
$projectVersions = array();
foreach($user->projects as $project)
{
$projectId = $project->pivot->project_id;
$projectVersions[] = Version::where('project_id', $projectId)
->where('created_by', $user->id)
->get();
}
return $projectVersions;
When I am using below code which is suggested by #John Lobo, it is returning below output:
{
"id": 2,
"name": "Hadayat Niazi",
"email": "niazicr801#gmail.com",
"is_admin": 0,
"email_verified_at": null,
"created_at": "2021-06-11T15:13:00.000000Z",
"updated_at": "2021-06-11T15:13:00.000000Z",
"projects": [
{
"id": 1,
"name": "Laravel",
"pivot": {
"user_id": 2,
"project_id": 1
},
"versions": [
{
"id": 1,
"title": "V1"
}
]
}
]
}
Displaying the user projects and versions:
Again I am updating the code for #John Lobo, he want to look the output
$user = User::with(['projects', 'projects.versions'])
->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return [
$project->versions,
];
});
return $result;
Output the code
[
[
[
{
"id": 1,
"title": "V1",
"project_id": 1,
"version": "1.22",
"created_by": 2,
"is_publish": 0,
"feature": "<b>In this ipdate asdsdasd</b>",
"bug_fix": "<p><b>sdfdffffffffff</b></p>",
"created_at": "2021-06-12T08:08:21.000000Z",
"updated_at": "2021-06-12T08:08:21.000000Z"
},
{
"id": 2,
"title": "v2",
"project_id": 1,
"version": "2.12",
"created_by": 2,
"is_publish": 0,
"feature": "adsdasdsadas",
"bug_fix": "sddasdas",
"created_at": null,
"updated_at": null
}
]
],
[
[]
]
]
In controller you can do the following.if you have relation in project model called version
$projectVersions=User::with(['projects','projects.version'])->find(auth()->user()->id);
return $projectVersions->projects;
I believe Project model has below relationship
public function version(){
return $this->hasMany(Version::class);
}
Updated
$user=User::with(['projects','projects.versions'])->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return $project->versions;
});
dd($result);
Use like below
$json = json_encode($responseOfController);
echo "<pre>";print_r($json);die;

How to read a nested json file in flutter and bind the values to dependent dropdowns

Json file has hierarchy as following:
[
{
"id": 1,
"city": "Mumbai",
"area": [
{
"id": 101,
"name": "Ghatkoapr",
"subArea": [
{
"id": 10101,
"name": "Pantnagar"
}
]
},
]
},
{
"id": 2,
"city": "Pune",
"area": [
{
"id": 201,
"name": "Shivajinagar",
"subArea": [
{
"id": 20101,
"name": "Model Colony"
}
]
}
]
}
]
I want to bind city value to first dropdown and its dependent areas to second dropdown and subareas to third dropdown.
I am new to flutter. I have tried many approaches but didnt help. Can someone help?

lodash sort an array of objects by a property which has an array of objects

I have a an object. I am able to sort the items by using lodash's _.orderBy().
However, in one of the scenario I have to sort by subject, which is an array of objects. Items inside the subject array are already sorted based on the name.
As subject is an array of the objects, I need to consider the first item for sorting.
[
{
"id": "1",
"name": "peter",
"subject": [
{
"id": "1",
"name": "maths"
},
{
"id": "2",
"name": "social"
}
]
},
{
"id": "2",
"name": "david",
"subject": [
{
"id": "2",
"name": "physics"
},
{
"id": "3",
"name": "science"
}
]
},
{
"id": "3",
"name": "Justin",
"subject": [
]
}
]
You can use _.get() to extract the name (or id) of the 1st item in subjects. If no item exists, _.get() will return undefined, which can be replaced with a default value. In this case, we don't want to use an empty string as a default value, since the order would change. Instead I'm checking if the value is a string, if it is I use lower case on it, if not I return it as is.
const arr = [{"id":"1","name":"peter","subject":[{"id":"1","name":"maths"},{"id":"2","name":"social"}]},{"id":"2","name":"david","subject":[{"id":"2","name":"physics"},{"id":"3","name":"science"}]},{"id":"3","name":"Justin","subject":[]}]
const result = _.orderBy(arr, o => {
const name = _.get(o, 'subject[0].name')
return _.isString(name) ? name.toLowerCase() : name
})
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Use _.sortBy with a comparison/sorting function argument. Your function itself can look into the receiving arguments subject key (I think its the subject you want to compare?)
Since you have the question also tagged with ES6 here is an JS only solution via Array.sort:
let arr = [ { "id": "1", "name": "peter", "subject": [ { "id": "1", "name": "maths" }, { "id": "2", "name": "social" } ] }, { "id": "2", "name": "david", "subject": [ { "id": "2", "name": "physics" }, { "id": "3", "name": "science" } ] }, { "id": "3", "name": "Justin", "subject": [] }, ]
const result = arr.sort((a,b) =>
a.subject.length && b.subject.length
? a.subject[0].name.localeCompare(b.subject[0].name)
: a.subject.length ? -1 : 1)
console.log(result)

Angular HTTP Res JSON Data print in html

Below is the HTTP get request response. how can i print same in view using *ngFor . iam trying to print single object print like data[0].value1 in console. it returns undefined. inside data array 3 JSON Objects. and some arrays also
Any help much appreciated...
getEmp(){
this.EmpService.getAccounts().subscribe((res : any[])=>{
this.products = JSON.stringify(res);
});
.
{
"data": [
{
"value1": "3546786908765432",
"category": "Clothing (Brand)",
"category_list": [
{
"id": "001",
"name": "Clothing (Brand)"
},
{
"id": "39324324230",
"name": "Boutique Store"
},
{
"id": "12342324324",
"name": "Website"
}
],
"name": "wqeqws",
"id": "qwsqwsq w",
"tasks": [
"ANALYZE",
"ADVERTISE",
"MODERATE",
"CREATE_CONTENT",
"MANAGE"
]
},
{
"value1": "111-9=-09876543",
"category": "Education",
"category_list": [
{
"id": "23456",
"name": "Education"
}
],
"name": "sdcsfcsdfvsd",
"id": "111111111111",
"tasks": [
"ANALYZE",
"ADVERTISE",
"MODERATE",
"CREATE_CONTENT",
"MANAGE"
]
}
],
"paging": {
"cursors": {
"before": "dsfsds",
"after": "sdfsfs"
}
}
}
this.products = res.data;
In your page
< *ngFor="let item of products >

Perl: Combine two JSONs

I am looking for help/guidance to combine multiple JSON into 1 JSON based on a node in PERL. For example here are the two JSON content that I want to combine.
JSON #1:
{
"title": "All",
"lastModified": "2017-04-11T00:00:00.000+0000",
"users": [{
"name": "Alpha One",
"title": "Security Chief",
"locations": [{"id": "730WLCS"}, {"id": "943MCS"}]
},
{
"name": "Alpha Two",
"title": "Security Manager"
}
]
}
JSON #2:
{
"title": "All",
"lastModified": "2017-04-11T00:00:00.000+0000",
"users": [{
"name": "Beta One",
"title": "Architect",
"locations": [{"id": "730WLCS"}]
}
]
}
RESULT JSON :
{
"title": "All",
"lastModified": "2017-04-11T00:00:00.000+0000",
"users": [{
"name": "Alpha One",
"title": "Security Chief",
"locations": [{"id": "730WLCS"}, {"id": "943MCS"}]
},
{
"name": "Alpha Two",
"title": "Security Manager"
},
{
"name": "Beta One",
"title": "Architect",
"locations": [{"id": "730WLCS"}]
}
]
}
Basically, I want to combine only the "users" node.
I tried to get the node using from_json and tried to push into an array, but it is not working.
Here is the code that I tried:
my $json_obj1 = from_json($json_txt1, {utf8 => 1});
my $json_obj2 = from_json($json_txt2, {utf8 => 1});
push(#myJSON, #{$json_obj1->{'users'}});
push(#myJSON, #{$json_obj2->{'users'}});
Any help is much appreciated.
Thank you.
my $json_obj1 = decode_json($json_txt1); # Same as from_json($json_txt1, {utf8 => 1})
my $json_obj2 = decode_json($json_txt2);
push #{ $json_obj2->{users} }, #{ $json_obj1->{users} };
If you want to remove duplicates , keeping the newer records (assuming $json_obj1 is the older state), you can use the following:
my %seen;
#{ $json_obj2->{users} } =
grep !$seen{$_->{name}}++,
#{ $json_obj2->{users} },
#{ $json_obj1->{users} };