Powershell Json object manipulation - json

I am hitting a Rest API and collected a gnarly block of Json. I'm running convertfrom-json on that to get a powershell object which I would like to manipulate. Essentially I need to prune a number of field/values.
Its no issue to 'get' the fields I want to remove from the object as I can just drill down to the field and collect the value thats easy, where I am stuck is how to trim off that field from the posh object. Would appreciate any assistance. Thanks.
Example:
$sample_json = #"
{
"fields": {
"field_one": 1,
"field_two": 2,
"field_three": "three",
"field_four": "remove_me",
"field_five": 5
}
}
"#
Clear-Host
$json_object = ConvertFrom-Json -InputObject $sample_json
$json_object
Gives:
fields
------
#{field_one=1; field_two=2; field_three=three; field_four=remove_me; field_five=5}
So the question is how can I remove "field_four" key, and it's value, from $json_object ? Apologies if this is crazy simple; I'm a bit out of touch with Powershell these last few years.

You can remove "field_four" with the Remove method from PSObject.Properties:
$json_object.fields.PSObject.Properties.Remove("field_four")

Use the following statement
$json_object.fields.PSObject.Properties.Remove("field_four")

Related

Powershell trouble getting value from key named count

I have a simple json that I am trying to get values from in Powershell
$webData = #'
{
"results": [
{
"facet": "266976",
"appid": "266976",
"count": 233206
},
{
"facet": "27096405",
"appid": "27096405",
"count": 85669
}
]
}
'#
$data1 = $webData | ConvertFrom-Json
Write-Output $data1.results.count
When I write output I get values count and not value itself like I do for appid and facet.
Desired result: 233206
Current result: 2
I cannot change json.
Is there a way for PS not to see it as a count operator?
Thank you
As mklement0 notes, in this case the array type's ICollection.Count property takes precedence over member access enumeration of the array-element property named Count.
A simple workaround is to use the intrinsic method .ForEach(string PropertyName):
$data1.results.ForEach('count')
As Santiago Squarzon notes, the type of ForEach() output is Collection`1. If you actually need an array, use the array sub-expression operator #() or use the workaround suggested by Santiago, using GetEnumerator().
$arrayOfCount = #($data1.results.ForEach('count'))
$arrayOfCount = $data1.results.GetEnumerator().Count
Output:
233206
85669
As Santiago Squarzon noted, if you actually want to get the value of count for the first object only, you can write:
$data1.results[0].Count
Output:
233206
Note that Write-Output is effectively redundant, because PowerShell implicitly outputs the "result" of any statement. So I've removed it in the samples above.

definition inside a property in invoke-restmethod (JSON Body)

I'm pretty stuck and can't find anything about it on the internet. I'm also not sure how to describe the thing i'm looking for, so maybe someone can help me.
I've got some code to create a ticket in TopDesk through API using invoke-restmethod in PS.
For the request field in TopDesk, I need some output stored in a variable, but if I want to use a variable in the PS command, I need to define the JSON body with the use of #{} | covertTo-JSON (found that somewhere on the internet).
Now this parameter I need to put through, has to have a definition. I need to give in in the value is a email or a name.
$json = #{
"callerLookup" = "{ email : email#domain.com }"
} | Convertto-JSON
Now the thing is, TopDesk doesn't see the "{ email : email#domain.com }" as a correct value.
Before, I just the following (which will work, but can't use variables):
$body = '{"email": "automation#rid-utrecht.nl"}'
I hope I described my problem cleary enough and hope that someone can help me.
Thanks in advance.
Kind regards,
Damian
For ConvertTo-Json to produce the serialized { "property" : "value" } syntax, you must pass it an object that has a property called property and an associated value equal to value. You can easily create this scenario with the [pscustomobject] accelerator.
$json = #{
callerLookup = [pscustomobject]#{email = 'email#domain.com'}
} | ConvertTo-Json

How to parse multidimensional JSON array in bash using jsawk?

I have an array like below. I want to parse entire data to my bash array.
So i can call the first "JSON addressLineOne" from ${bashaddr[0]}, and etc.
[
{
"id":"f0c546d5-0ce4-55ee-e043-516e0f0afdc1",
"cardType":"WMUSGESTORECARD",
"lastFour":"1682",
"cardExpiryDate":"2012-01-16",
"firstName":"robert",
"lastName":"robishaw",
"addressLineOne":"Apt venue",
"addressLineTwo":"",
"city":"oakdale",
"state":"CT",
"postalCode":"06370",
"phone":"534534",
"isDefault":false
},
{
"id":"f0c546d5-0ce0-55ee-e043-516e0f0afdc1",
"cardType":"MASTERCARD",
"lastFour":"2731",
"cardExpiryDate":"2009-08-31",
"firstName":"robert",
"lastName":"robishaw",
"addressLineOne":"119 maple ave.",
"addressLineTwo":"",
"city":"uncasville",
"state":"CT",
"postalCode":"06382",
"phone":"7676456",
"isDefault":false
},
{
"id":"f0c546d5-0ce2-55ee-e043-516e0f0afdc1",
"cardType":"MASTERCARD",
"lastFour":"6025",
"cardExpiryDate":"2011-08-31",
"firstName":"robert",
"lastName":"robishaw",
"addressLineOne":"Angeline Street",
"addressLineTwo":"",
"city":"oakdale",
"state":"CT",
"postalCode":"06370",
"phone":"7867876",
"isDefault":false
}
]
I have tried like this:
#!/bin/bash
addressLineOne="$(echo $card | jsawk 'return this.addressLineOne')"
but it gives me the entire address:
["address 1","address 2","address 3"]
Thank you.
I wrote the answer below before reading the comments, but this is exactly the same answer as #4ae1e1 provided, except I don't put -r tag in case you want the values to remain quoted (e.g. passing this as an argument somewhere else).
I know this is not jsawk, but do consider jq:
jq '.[].addressLineOne' yourfile.txt
And to access specific values you can put record number in the square brackets (starting with 0 for the first address and so on). For example to get the address for the third record:
jq '.[2].addressLineOne' yourfile.txt
For learning more about jq and advanced uses, check: http://jqplay.org
What you need to do is make use of the -a switch to apply some post processing and filter the output array like this:
jsawk 'return this.addressLineOne' -a 'return this[0]'
From the documentation:
-b <script> | -a <script>
Run the specified snippet of JavaScript before (-b) or after (-a)
processing JSON input. The `this` object is set to the whole JSON
array or object. This is used to preprocess (-b) or postprocess
(-a) the JSON array before or after the main script is applied.
This option can be specified multiple times to define multiple
before/after scripts, which will be applied in the order they
appeared on the command line.

ConvertFrom-Json Loop Through Object

I am pretty new to PowerShell and have the following code:
$jsonResponse = #"
{
"departments":[{"id":81,"department":"Sales"},{"id":61,"department":"IT Support"}]
}
"#
$myCustomObject = $jsonResponse | ConvertFrom-Json
$myCustomObject.departments.department[0]
$myCustomObject.departments.department[1]
Which allows me to access elements of the customObject (converted from JSON).
What I need is the ability to loop through the object so I can access each element i.e.
object_loop
{
$myCustomObject.departments.department[x]
}
where x is the loop increment.
Sorry of this is silly question but I have googled and can't find a simple example.
Cheers for any help.
Duncs
It is as trivial as
foreach($obj in $myCustomObject.departments)
{
Write-Host ("Got" + $obj.department)
}

Decode a JSON file with PHP

I have a classic JSON problem, and i know that many post are asking about that...
But i doubt that the JSON i try to grab has a correct structure.
The files Begin like that :
[{
"time":"0-12h",
"articles":[
{
"id":1,
"domain_id":22,
"title":"Hi Guys"
}
{
"id":2,
"domain_id":17,
"title":"Hi everyone"
}
]
}]
I have try a lot of combinaison to echo the title :
$data = json_decode($json, true);
echo $data->articles;
Or
echo $data->articles->title;
Or
echo $data->articles[0]->title;
Nothing works... :(
Can you help me ?
Thanks !
The second argument true to json_decode() means it should create associative arrays rather than objects for {} in the JSON. So in addition to dealing with the indexed arrays as Explosion Pills points out, you also need to use array syntax to access the keyed elements:
$data[0]['articles'][0]['title']
If you want to be able to use -> syntax, leave out the second argument or set it to false.
I'm hoping the missing comma in the JSON is an error when transcribing to the question. If not, you also need to fix the code that creates the JSON in the first place.
$data itself is an array. Try
$data[0]->articles[0]->title;
Also the JSON is not valid (missing a comma before the second articles array element).
there is a comma , missing
}
,
{
json_decode with the second parameter true returns an array
print_r($data['articles']);
echo $data['articles'] would output Array