Search code examples
powershellazure-powershellazure-automationazure-runbookinvoke-webrequest

how to parse JSON response using power shell?


I'm looking for parsing JSON respoonse with powershell ruuning on azure runbook., The following is my code.

$servicePrincipalConnection=Get-AutomationConnection -Name "AzureRunAsConnection"         
Connect-AzAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint | Write-Verbose

$uri = 'https://nseindia.com//emerge/homepage/smeNormalMktStatus.json'
$result = Invoke-WebRequest -Uri $uri -UseBasicParsing
Write-Output $result
$result = $result.Content
Write-Output $result
Write-Output $result.NormalMktStatus
Write-Output 'saranaraj kumar'
# Stop-AzStreamAnalyticsJob -Name SQLCDCProcessor -ResourceGroupName RealTimeAnalytics

The following is my JSON response

StatusCode        : 200
StatusDescription : OK
Content           : {"NormalMktStatus":"open"}
RawContent        : HTTP/1.1 200 OK
                    X-FRAME-OPTIONS: SAMEORIGIN
                    Pragma: no-cache
                    Connection: keep-alive
                    Content-Length: 26
                    Cache-Control: max-age=0, no-cache, no-store
                    Content-Type: application/json
                    Date: Fri, 27 ...
Forms             : 
Headers           : {[X-FRAME-OPTIONS, SAMEORIGIN], [Pragma, no-cache], [Connection, keep-alive], [Content-Length, 
                    26]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : 
RawContentLength  : 26
{"NormalMktStatus":"open"}
saranaraj kumar

From power i'm getting JSOn reponse as above, I can read response.content that contains {"NormalMktStatus":"open"} but if I'm using response.content.normalMKTstatus I'm getting empty space. how to resolve it? And also I wanna do if-else condition with power shell that is

if(response.content.normalMKTstatus -eq 'open')
    {
    write-output true
    }
    else
    {
    write-output false
    }

Solution

  • If you use $result =Invoke-WebRequest..., $result.Content contains a JSON string in your case, which you first need to parse into objects in order to be able to access properties with dot notation (.normalMktStatus).

    While you could use ConvertFrom-Json to perform this parsing, it is simpler to use the
    Invoke-RestMethod cmdlet, which performs the JSON parsing behind the scenes and directly returns an object (of type [pscustomobject]) representing the JSON content
    :

    $obj = Invoke-RestMethod https://nseindia.com//emerge/homepage/smeNormalMktStatus.json
    
    $obj.NormalMktStatus # -> 'open'
    
    if ($obj.NormalMktStatus -eq 'open') {
      $true
    }
    else {
      $false 
    }