-2

How to call API inside function. this is my url https://www.gov.uk/bank-holidays.json. I am new for powershell can you help me to do this.

function Holiday {
 
   $list = Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json
   Write-Host "$list"

}

but i am unable to list . can u please help me on that

mklement0
  • 312,089
  • 56
  • 508
  • 622

1 Answers1

0

Invoke-RestMethod automatically parses the API's JSON response into an object [graph] - a nested [pscustomobject] instance.

While very convenient for subsequent OO processing, such an object's display representation isn't very helpful.

You can simply convert back to JSON in order to visualize the result:

function Get-Holiday {
 
  # Call the API, which returns JSON that is parsed into a [pscustomobject]
  # graph, and return (output) the result.
  Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json

}

$list = Get-Holiday

# Visualize the object for display by converting it back to JSON.
$list | ConvertTo-Json -Depth 3

Note the unfortunate need to specify -Depth 3 explicitly - see this question.

With respect to processing, here's an example that accesses the first entry for England and Wales:

$list.'england-and-wales'.events[0]

The above yields:

title          date       notes bunting
-----          ----       ----- -------
New Year’s Day 2015-01-01          True
mklement0
  • 312,089
  • 56
  • 508
  • 622
  • `JSON` parsing in powershell is done this way? is this methodology specific to `JSON`? – Nicholas Saunders Nov 18 '20 at 05:24
  • Hi, i need to get date value from all objects like english-and-wales, scotland , northern ireland. using this $list.'england-and-wales'.events.date i will get only england-and-wales details but remaining scotland, northern ireland date i am unable to fetch – AFFISH MOHAMMAD Nov 18 '20 at 09:52
  • @NicholasSaunders: `ConvertFrom-Json` and `Invoke-RestMethod` (with JSON responses) parse the JSON into an object model using `[pscustomobject]`, and you can access that object model with regular dot notation. – mklement0 Nov 18 '20 at 13:07
  • @AFFISHMOHAMMAD: `$list.scotland.events[0]` and `$list.'northern-ireland'.events[0]` Again, if you need further assistance, II encourage you to ask a _new_ question. – mklement0 Nov 18 '20 at 13:10