I have a json that I wanted to generate using Powershell
{
"CreatedBy": "div",
"Label": "jss key",
"Scopes": ["content-#everything#", "audience-delivery"]
}
I am using the below to generate the json but it is not successful
$EdgeClientID = 'fsfsdfSDFsda'
$scope = '[ "content-#everything#", "audience-delivery" ]'
$body = #{
'CreatedBy' = $EdgeClientID
'Label' = 'jss key'
'Scopes' = $scope
} | ConvertTo-Json
the result I am getting is
{
"CreatedBy": "fsfsdfSDFsda",
"Label": "jss key",
"Scopes": "[\"content-#everything#\", \"audience-delivery\"]"
}
The value of scope is not coming right. Can someone please help?
The reason why you're not getting the desired output from it is because the following is an array only in the context of JSON and not in the context of PowerShell and ConvertTo-Json interprets it a simple string:
$scope = '[ "content-#everything#", "audience-delivery" ]'
The following should fix the problem:
$EdgeClientID = 'fsfsdfSDFsda'
$scope = "content-#everything#", "audience-delivery"
$body = #{
'CreatedBy' = $EdgeClientID
'Label' = 'jss key'
'Scopes' = $scope
} | ConvertTo-Json
You could also create a blue print class for your JSON:
class JSONBluePrint {
[string]$CreatedBy
[string]$Label
[object[]]$Scopes
JSONBluePrint () { }
JSONBluePrint([string]$CreatedBy, [string]$Label, [object[]]$Scopes)
{
$this.CreatedBy = $CreatedBy
$this.Label = $Label
$this.Scopes = $Scopes
}
[string] ToJson () {
return $this | ConvertTo-Json -Depth 100
}
}
[JSONBluePrint]::new(
'div',
'jss key',
#('content-#everything#', 'audience-delivery')
).ToJson()
$json = [JSONBluePrint]::new()
$json.CreatedBy = 'div'
$json.Label = 'jss key'
$json.Scopes = 'content-#everything#', 'audience-delivery'
$json.ToJson()
Related
I have a Laravel array and would like to modify the returned values.
$array = ['hr-34', 've-53', 'dv-65'];
I want to remove everything before the dash and the dash itself and return the following array.
$array = ['34', '53', '65'];
You can do something like this:
foreach ($c as $key => $value) {
$pieces = explode('-', $value);
$array[$key] = $pieces[1];
}
You have used the tag collections. So if it's a collection you can use this function:
$c->map(function ($item) {
return explode('-', $item)[1];
})
Steps to follow:
define blank array $new_array (to fill single value from foreach loop).
get single value using foreach loop.
use strstr for remove everything before dash and remove '-' using str_replace.
fill single value in $new_array.
return $new_array outside foreach loop.
Below is the code -
$array = ['hr-34', 've-53', 'dv-65'];
$new_array = array();
foreach($array as $key=>$result){
$data = str_replace('-', '', strstr($result, '-'));
$new_array[]= $data;
}
print_r($new_array);
That's all!
https://www.php.net/manual/en/function.array-map.php
https://www.php.net/manual/en/function.explode.php
$array = array_map(function ($item) {
return explode('-', $item)[1];
}, $array)
Edit:
As you changed title from array to collection you can use:
https://laravel.com/docs/9.x/collections#method-map
$collection->map(...)
in a similar way to array_map(...)
$array = ['hr-34', 've-53', 'dv-65'];
$array = collect($array)
->map(fn($item) => explode('-', $item)[1])
->all();
/**
* array:3 [
* 0 => "34"
* 1 => "53"
* 2 => "65"
* ]
*/
dd($array);
Here this code in sandbox
you can use regex with preg_replace as :
$new = array_map(function ($item) {
return preg_replace('/^([^-])+-/', '', $item);
}, $array);
result :
array:3 [
0 => "34"
1 => "53"
2 => "65"
]
I am trying to pass a multi-dimensional array as a query parameter in the below URL:
{{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl_slug_params[0][0]=test&addl_slug_params[0][1]=test1&addl_slug_params[0][2]=test0
what is wrong with the above URL?
My code to access these parameters in Laravel 6.0 is below:
$addl_slug_params = $request->query('addl_slug_params');
$i=0;
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
print_r('addl_slug_params : ('.$i.':'.$j.') : '.$asp); die();
$j=$j+1;
}
$i = $i+1;
}
Result:
addl_slug_params : (0:0) : test
Problem: test1 and test0 are not accessible..
What should I do?
The problem is the die(); after printr(), the loop will run once, aka only addl_slug_params : (0:0) : test
To help you visualize it better, I added an extra break after each loop:
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
echo('addl_slug_params : ('.$i.':'.$j.') : '.$asp);
echo nl2br(PHP_EOL);
$j=$j+1;
}
$i = $i+1;
}
Will result in the following:
addl_slug_params : (0:0) : test
addl_slug_params : (0:1) : test1
addl_slug_params : (0:2) : test0
here is a solution for multi-dimensional arrays. Developed in 2~ hours, definitely needs improvement but hopefully helps you out :)
Route::get('example', function (\Illuminate\Http\Request $request) {
$addl_slug_params = [
[
1 => [
'title' => 'Test 1',
'slug' => 'test1'
],
2 => [
'title' => 'Test 2',
'slug' => 'test2'
],
3 => [
'title' => 'Test 3',
'slug' => 'test3'
],
],
];
// Encode
$prepend = 'addl_slug_params';
$query = "?$prepend";
$tempSlugs = $addl_slug_params[0];
$lastIndex = count($tempSlugs);
foreach ($addl_slug_params as $pIndex => $params) {
foreach ($params as $sIndex => $slugData) {
$tempQuery = [];
foreach ($slugData as $sdIndex => $data) {
// Replace '-' or ' -' with ''
$encodedString = preg_replace('#[ -]+#', '-', $data);
// title = test1
$tempString = "$sdIndex=$encodedString";
$tempQuery[] = $tempString;
}
$dataQuery = implode(',', $tempQuery);
$appendStr = ($sIndex !== $lastIndex) ? "&$prepend" : '';
// Set the multidimensional structure here
$query .= "[$pIndex][$sIndex]=[$dataQuery]$appendStr";
}
}
// DECODE
// ?addl_slug_params[0][1]=[title=Test-1,slug=test1]&addl_slug_params[0][2]=[title=Test-2,slug=test2]&addl_slug_params[0][3]=[title=Test-3,slug=test3]
$slugParams = $request->query('addl_slug_params');
$slugParamData = [];
foreach ($slugParams as $slugItems) {
foreach ($slugItems as $slugItem) {
// Replace [title=test,slug=test1] into 'title=test,slug=test1' and explode
// into into an array, and split title=test into [title => test]
$splitArray = explode(',', (str_replace(array('[', ']'), '', $slugItem)));
$slugItemData = [];
foreach ($splitArray as $value) {
$data = explode('=', $value);
$slugItemData[$data[0]] = $data[1];
}
$slugParamData[] = $slugItemData;
}
}
dd($slugParamData);
});
I have solved the problem using associative arrays as it gives more flexibility and Garrett's solution definitely helped
new url: {{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl[users][params]=name
laravel code:
`
foreach ($addl_data_array as $addl_slug => $addl_slug_data) {
foreach ($addl_slug_data as $key => $value) {
$params = null;
$where_raw = null;
$where_has = null;
$with_relationships = null;
$with_timestamps = null;
}
}
`
How would you break down the following json variable into individual items in array?
[
{
"server":{
"name":"myUbuntuServer1",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
},
{
"server":{
"name":"myUbuntuServer2",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
},
{
"server":{
"name":"myUbuntuServer3",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
}
]
For instance, the above would translate to an array, with the following items:
Array-item 0
{
"server":{
"name":"myUbuntuServer1",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
}
Array-item 1
{
"server":{
"name":"myUbuntuServer2",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
}
Array-item 2
{
"server":{
"name":"myUbuntuServer3",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
}
I would like to accomplish this in Powershell 2.0 and access each one individually. So far this is what I've managed to accomplish:
$jsonarr = #()
$arr = (Get-Content C:\json.json| Out-String).replace("[","") -split "(})," -replace "]",""
$jsonarr += $arr[0..1] -join ""
$jsonarr += $arr[2..3] -join ""
$jsonarr += $arr[4]
However this is extremely inflexible, and will cease to work the minute I had another server's detail to the JSON file.
for PowerShell v2 you can use Convert between PowerShell and JSON
PS
PowerShell v3+, should be the same using the tool above:
$json = '[
{
"server":{
"name":"myUbuntuServer1",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
},
{
"server":{
"name":"myUbuntuServer2",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
},
{
"server":{
"name":"myUbuntuServer3",
"imageRef":"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001",
"flavorRef":"6"
}
}
]'
$servers = ConvertFrom-Json $json
$servers.server.imageRef
returns
3afe97b2-26dc-49c5-a2cc-a2fc8d80c001
3afe97b2-26dc-49c5-a2cc-a2fc8d80c001
3afe97b2-26dc-49c5-a2cc-a2fc8d80c001
Also, don't forget "Get-Member"
PPS
PS C:\Users\joshua\Desktop> $servers.server| where name -EQ myUbuntuServer2
name imageRef flavorRef
---- -------- ---------
myUbuntuServer2 3afe97b2-26dc-49c5-a2cc-a2fc8d80c001 6
PS C:\Users\joshua\Desktop> $servers.server| where name -EQ myUbuntuServer2 | select -Property flavorRef
flavorRef
---------
6
PPPS
also ofcourse
$servers.server[0]
you should be able to index by name also but I'm making some silly error atm
I have the following script:
$serverList = #{
"Server1Name" = #{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server2Name" = #{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server3Name" = #{ "WindowsService1" = "Status" };
"Server4Name" = #{ "WindowsService1" = "Status" };
"Server5Name" = #{ "WindowsService1" = "Status" };
"Server6Name" = #{ "WindowsService1" = "Status" }
}
$copy = $serverList.Clone()
foreach ($server in $copy.Keys) {
foreach ($service in $copy[$server].Keys) {
$serviceInfo = Get-Service -ComputerName $server -Name $service
$serverList[$server][$service] = $serviceInfo.Status
}
}
I made sure that I am not modifying the hashtable that is being enumerated, but yet I still get this error when I run the script:
Collection was modified; enumeration operation may not execute.At line:14 char:14
+ foreach ($service in $copy[$server].Keys) {
+ ~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException
I read up on this here: http://blog.matticus.net/2013/11/powershell-clearing-values-within.html. If I copy the code form there, it executes without error for me.
Could my problem have something to do with nested foreach loops? Is there a mistake in my code? Can anyone shed any light on this?
Powershell does not like that you are modifying the collection which you are iterating over.
In the beginning you made a clone called $copy to avoid this problem. The clone() is a "shallow copy", thus the objects being refered to for each key are the same in your copy.
On this line:
$serverList[$server][$service] = $serviceInfo.Status
You modify the inner collection - which you are currently iterating over.
In fact, the outter collection is never modified, only referred to, so the outter clone() call is unneccessary. Instead, you should clone the inner collection.
Something like this (untested):
$serverList = #{
"Server1Name" = #{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server2Name" = #{ "WindowsService1" = "Status"; "WindowsService2" = "Status" };
"Server3Name" = #{ "WindowsService1" = "Status" };
"Server4Name" = #{ "WindowsService1" = "Status" };
"Server5Name" = #{ "WindowsService1" = "Status" };
"Server6Name" = #{ "WindowsService1" = "Status" }
}
foreach ($server in $serverList.Keys) {
$copy = $serverList[$server].clone();
foreach ($service in $copy.Keys) {
$serviceInfo = Get-Service -ComputerName $server -Name $service
$serverList[$server][$service] = $serviceInfo.Status
}
}
I was surprised that the .Clone() method just creates a new reference to the same object, it does not create a new object with the same properties. I couldn't find an easy way to actually copy an entire hashtable, rather than cloning it. So I wrote a function to do this:
Function Copy-HashTable($HashTable) {
$newHash = #{}
$HashTable.GetEnumerator() | ForEach-Object {
if ($_.Value -is "Hashtable") {
$newHash[$_.Key] = Copy-HashTable $_.Value
} else {
$newHash[$_.Key] = $_.Value
}
}
$newHash
}
Applying this to your code, you would just need to replace the line
$copy = $serverList.Clone()
with
$copy = Copy-HashTable $ServerList
I am trying to store the FBIDs of a Facebook user's friends in the column of a mysql database. I've tried looking up other answer on this issue, and I have tried to implement it (in Laravel 4). Here is what I have done:
In the Facebook.php file, one of the providers:
'friends' => 'https://graph.facebook.com/me/friends?access_token='.$token->access_token
In my Oauth2 Controller:
$friends_list = $user['friends'];
$friends_list_array = json_decode($friends_list,true);
$arr= $friends_list_array['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
$friend_ids_arr[] = $friend['id'];
}
$friend_ids = implode("," , $friend_ids_arr);
And then I want to store the $friend_ids object in a "text" column in my database. However, when running this, I keep getting the error: Invalid argument supplied for foreach()
But it is very clearly being supplied an array as it should. Is there something I'm not seeing? Thank you for your help.
Actually the returned result is a json, the returned object should look something like this
{
"id": "xxxxxxx",
"name": "Sheikh Heera",
"friends": {
"data": [
{ "name": "RaseL KhaN", "id": "xxx" },
{ "name": "Yizel Herrera", "id": "xxx" }
],
"paging": {
"next": "https://graph.facebook.com/xxx/friends?limit=..."
}
}
}
After you json_decode
$user = json_decode($user, true);
It should look something like
Array
(
[id] => xxxxxxx
[name] => Sheikh Heera
[friends] => Array
(
[data] => Array
(
[0] => Array
(
[name] => RaseL KhaN
[id] => xxx
)
[1] => Array
(
[name] => Yizel Herrera
[id] => xxx
)
)
[paging] => Array
(
[next] => https://graph.facebook.com/xxx/friends?limit=...
)
)
)
So, now you can
$friends_list = $user['friends'];
$data = $friends_list['data'];
Make sure your $data array is not empty and then loop
if(count($data)) {
$friend_ids_arr = array();
foreach($data as $friend) {
$friend_ids_arr[] = $friend['id'];
}
}
So, the foreach will run only when $data has items in it.
Update: It may help you
$url = "https://graph.facebook.com/me?fields=id,name,friends&access_token=YOUR_ACCESS_TOKEN";
$contents = json_decode(file_get_contents($url), true);
$friends = $contents['friends'];
$friend_ids_arr[]
foreach($friends['data'] as $friend)
{
$friend_ids_arr[] = $friend['id'];
}