I'm trying to convert this :
tags: [
{ tagName : "O365" },
{ tagName : "Skype for Business" }
]
to "O365,Skype for Business" as a string.
Could anyone help me to accomplish this using Powershell ?
Works only if you have only one "tags" property in your JSON :
$json = #"
{
tags: [
{ tagName : "O365" },
{ tagName : "Skype for Business" }
]
}
"#
(ConvertFrom-Json $json | % tags | % tagName) -Join ", "
# result : O365, Skype for Business
Similarly,
$separator = ","
$tagname = (ConvertFrom-Json $json).tags.tagName
[String]::Join($separator,$tagname)
Or as a one-liner
[String]::Join(",",(ConvertFrom-Json $json).tags.tagName)
Related
Basically I formed an array of data based on certain conditions inside a loop and arrary data is something like this:
student1 RL123 S12 student2 RL423 S32 student6 RL166 S02 student34 RL993 P12 student99 RL923 S12
Above array data needs to be converted to JSON as below:
{
"Name" : "student1"
"RollNo" : "RL123"
"SubjectID" : "S12"
},
{
"Name" : "student2"
"RollNo" : "RL423"
"SubjectID" : "S32"
},
{
"Name" : "student6"
"RollNo" : "RL166"
"SubjectID" : "S02"
},
{
"Name" : "student34"
"RollNo" : "RL993"
"SubjectID" : "RL993"
},
{
"Name" : "student99"
"RollNo" : "RL923"
"SubjectID" : "S12"
}
If indeed your array is an array of strings (let's call it $students), you can skip the below line.
However, the way you have formatted it in your question makes it a string with space-separated items, so if that is the case, we should create a proper array from it by splitting on the whitespaces:
$students = 'student1 RL123 S12 student2 RL423 S32 student6 RL166 S02 student34 RL993 P12 student99 RL923 S12' -split '\s+'
Now just iterate over the values in the array and create objects using 3 array elements on each object:
$data = for ($i = 0; $i -lt $students.Count; $i+=3) {
[PsCustomObject]#{
Name = $students[$i]
RollNo = $students[$i + 1]
SubjectID = $students[$i + 2]
}
}
# here you convert the object array to JSON
$data | ConvertTo-Json
Output:
[
{
"Name": "student1",
"RollNo": "RL123",
"SubjectID": "S12"
},
{
"Name": "student2",
"RollNo": "RL423",
"SubjectID": "S32"
},
{
"Name": "student6",
"RollNo": "RL166",
"SubjectID": "S02"
},
{
"Name": "student34",
"RollNo": "RL993",
"SubjectID": "P12"
},
{
"Name": "student99",
"RollNo": "RL923",
"SubjectID": "S12"
}
]
the opening [ and closing ] denote that we're dealing with an array in Json syntax
For example, in the following PSCustomObject, I wish to remove the objects for which TagName does not exist
$dataset1 = #(
#{
MachineName = "AAA"
ID = "111"
TagName = "GroupA"
},
#{
MachineName = "BBB"
ID = "222"
TagName = "GroupB"
},
#{
MachineName = "CCC"
ID = "111"
TagName = ""
},
#{
MachineName = "DDD"
ID = "333"
TagName = ""
},
#{
MachineName = "EEE"
ID = "111"
TagName = ""
}
}
So, after deletion the $dataset1 should contain the following:
$dataset1 = #(
#{
MachineName = "AAA"
ID = "111"
TagName = "GroupA"
},
#{
MachineName = "BBB"
ID = "222"
TagName = "GroupB"
}
}
You can use Where-Object(or alias name where). Where-Object returns all objects for which the script block statement is true
$dataset1 = $dataset1 | Where-Object { $_.TagName }
I wanted to fetch array element and store in Perl variable. If I put 0 in replace of ? in $cur->{Type}[?]->{_id} I'm able to get only one array element but I want all. below is my collection
{
"_id" : ObjectId("5b7fdb050cc3c23478005741"),
"DBName" : "sample",
"DBServerURL" : "mongodb://localhost:27017/",
"Type" : [
{
"_id" : ObjectId("5b801dc963f8c81df83891bd")
},
{
"_id" : ObjectId("5b801dc963f8c81df83891be")
},
{
"_id" : ObjectId("5b801dc963f8c81df83891bf")
},
{
"_id" : ObjectId("5b801dc963f8c81df83891c0")
}
]
}
I'm trying to get ObjectId from all fields
$cursor = $CustColl->find(
{DBName => "sample",DBServerURL => "mongodb://localhost:27017/"},{'_id' => 1, 'Type.$._id' => 1, 'DBServerURL' => 1, 'DBName' => 1}
);
while(my $cur = $cursor->next){
my $cid = "$cur->{_id}" ;
my $jid = "$cur->{Type}[?]->{_id}" ;
my $url = "$cur->{DBServerURL}" ;
my $name = "$cur->{DBName}" ;
print "$cid : $jid : $url : $name\n" ;
}
I wanted an output like below:
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891bd : mongodb://localhost:27017/ sample
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891be : mongodb://localhost:27017/ sample
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891bf : mongodb://localhost:27017/ sample
5b7fdb050cc3c23478005741 : 5b801dc963f8c81df83891c0 : mongodb://localhost:27017/ sample
You are almost there. First, I fixed up your data to make it JSON but that's not a big deal:
my $json = q([{
"_id" : "5b7fdb050cc3c23478005741",
"DBName" : "sample",
"DBServerURL" : "mongodb://localhost:27017/",
"Type" : [
{
"_id" : "5b801dc963f8c81df83891bd"
},
{
"_id" : "5b801dc963f8c81df83891be"
},
{
"_id" : "5b801dc963f8c81df83891bf"
},
{
"_id" : "5b801dc963f8c81df83891c0"
}
]
} ]);
use JSON::XS;
my $perl = decode_json( $json );
That's a JSON array so you can go through it one element at a time. In Perl that shows up as an array reference Using the postfix dereference introduced in v5.20 makes this palatable (but not so hard without it):
while(my $cur = shift $perl->#*){ # or #$perl
my $cid = $cur->{_id} ;
my $url = $cur->{DBServerURL} ;
my $name = $cur->{DBName} ;
foreach my $hash ( $cur->{Type}->#* ) { # or #{ $cur->{Type} }
my $jid = $hash->{_id};
print "$cid : $jid : $url : $name\n" ;
}
}
The trick is that the $jid stuff is in another array and you want to go through those individually. There's a foreach inside the while to do that. It runs once for each of those and outputs the lines.
I am trying to build a Powershell array containing a single hashtable.
$params = #{
"name" = "bob"
"age" = "30"
}
$params | ConvertTo-Json
current output:
{
"age": "30",
"name": "bob"
}
Desired output:
[
{
"age": "30",
"name": "bob"
}
]
Try it this way:
$params = #{
"name" = "bob"
"age" = "30"
}
ConvertTo-Json #($params)
The #() syntax makes it an array.
You have to give the ConvertTo-Json cmdlet the input as a parameter, because the pipeline will automatically "unroll" the array and you'll be right back where you started.
I am brand new to perl. I am trying to grab a string out of some JSON output. My code below works, but seems like there is a smarter way to do this. Here is a sample of the JSON
$VAR1 = '{
"hasDetailRows" : true,
"reportMetadata" : {
"reportFormat" : "TABULAR",
"detailColumns" : [ "SUBJECT", "COMMENT_CREATED_DATE", "CASE_COMMENT_CREATED_BY" ],
"reportBooleanFilter" : null,
"reportFilters" : [ {
"column" : "CASE_COMMENT_CREATED_BY",
"operator" : "equals",
"value" : "Username"
} ],
"aggregates" : [ "RowCount" ],
"groupingsDown" : [ ],
"groupingsAcross" : [ ],
"developerName" : "My_Comments",
"reportType" : {
"type" : "CaseList",
"label" : "Cases"
},
"name" : "My Comments",
"id" : "REDCATED",
"currency" : null
},
"factMap" : {
"T!T" : {
"rows" : [ {
"dataCells" : [ {
"value" : "ID",
"label" : "Description"
}, {
"value" : "2014-02-17T22:01:17Z",
"label" : "2/17/2014 4:01 PM"
}, {
"value" : "USER ID",
"label" : "User Name"
} ]
}`
What I need is that label with the timestamp.
And here is my code
#!/usr/bin/perl
use warnings;
use strict;
use WWW::Mechanize;
use WWW::Salesforce;
use Data::Dumper;
use JSON -support_by_pp;
use 5.010;
use Date::Parse;
my $mech = WWW::Mechanize->new();
$mech->agent('Mozilla/5.0');
# Authenticate first via SOAP interface to get a session ID:
my $sforce = eval { WWW::Salesforce->login(
username => 'REDACTED',
password => 'REDACTED' ); };
die "Could not login to SFDC: $#" if $#;
# Get the session ID:
my $hdr = $sforce->get_session_header();
my $sid = ${$hdr->{_value}->[0]}->{_value}->[0];
#Our request
$mech->add_header( "Authorization" => "OAuth $sid" );
$mech->add_header( "X-PrettyPrint" => '1' );
$mech->get("SOME URL THAT RETURNS JSON");
my $content = $mech->content;
my $json = new JSON;
my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($content);
Here is what I have currently that grabs the value that I want from $content. All I need is the first result which is why I am killing the loop after the first run. Everytime I have tried this without a loop I get "Not a HASH reference". So all I need to know is the correct syntax for printing out the value of $timestamp.
foreach my $field(#{$json_text->{factMap}->{'T!T'}->{rows}}){
my $now = time();
my $timestamp = str2time($field->{dataCells}[1]->{'label'});
my $diff = int (($now - $timestamp)/60);
my $current = getLoggingTime();
print $current . " \t";
say "Time since last activity: " . $diff . " minutes!" ;
last;
}
sub getLoggingTime {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
my $nice_timestamp = sprintf ( "%04d-%02d-%02d %02d:%02d:%02d",
$year+1900,$mon+1,$mday,$hour,$min,$sec);
return $nice_timestamp;
}
I don't know what your without-a-loop version looks like, but this should work:
my $timestamp = str2time(
$json_text->{factMap}{'T!T'}{rows}[0]{dataCells}[1]{label}
);
Currently, you're looping over the elements of the array referenced by
$json_text->{factMap}{'T!T'}{rows}
...and stopping at the first entry
$json_text->{factMap}{'T!T'}{rows}[0]
...and dereferencing that to get to
$json_text->{factMap}{'T!T'}{rows}[0]{dataCells}[1]{label}