Extracting data from api using powershell tool Invoke-RestMethod - json

I am trying to get JSON details from an api using powershell.
I do not have any expereince with power shell, but I guess Invoke-RestMethod would be helpful.
the api I am trying to use is :
api.spotcrime.com/crimes.json?lat=30.639155&lon=-96.3647937&radius=0.02&key=spotcrime-private-api-key

Please read the online documentation: Invoke-RestMethod
Here is a sample showing how to access the data returned from this API:
$uri = 'api.spotcrime.com/crimes.json'
$params = #{
lat = '30.639155'
lon = '-96.3647937'
radius = '0.02'
key = 'spotcrime-private-api-key'
}
$crimes = Invoke-RestMethod -Uri $uri -Body $params |
Select-Object -ExpandProperty crimes
$crimes | Format-Table -AutoSize
In this dataset we have an object named crimes which contains an array of records. Expanding the crimes object and storing it to a $crimes variable will allow us to work with the records more easily.
Notice how Invoke-RestMethod automatically detects and converts JSON into objects. No need to use ConvertFrom-Json.

Related

Parsing a JSON Byte Stream Returned from a Web Request using Powershell without writing to a file

I'm using the following Powershell to call a URL that returns a JSON file. (If you were to paste the URL into the browser it would download a file, rather than display the raw JSON):
$fileName = "output.json"
$url = "https://some-url-that-returns-a-json-file-byte-stream"
$jsonFileResponse = Invoke-WebRequest -Method GET -Uri $url -UseDefaultCredentials -OutFile "output.json"
$parsedData = Get-Content -Path $fileName | ConvertFrom-Json
This works fine, and I get my parsed data at the end.
I was wondering, is there a way of doing this without involving the file system, i.e. without having the step of outputting to output.json first, and instead handling this in-memory and without any disk i/o?
The question is less one of converting to 'JSON' and more of just converting to text.
Using [System.Text.Encoding]::ASCII.GetString seems to do the trick.
$url = "https://some-url-that-returns-a-json-file-byte-stream"
$jsonFileResponse = Invoke-WebRequest -Method GET -Uri $url -UseDefaultCredentials
$parsedData = [System.Text.Encoding]::ASCII.GetString($jsonFileResponse.Content) | ConvertFrom-Json

Access members of an object one by one

in Powershell I have an object from query response, and it contains multiple members. I have to add some strings before and after every member of the object, and then send the produced json as query to create similar rules for different service. What happens is that $l_rules_json = $l_rules | ConvertTo-Jsondoes not access single member of the object but all members. How do I access members one by one in the cycle?
$l_rules |
ForEach-Object {
write-host("Output from rules objects in a cycle")
$l_rules_json = $l_rules | ConvertTo-Json
$l_rules_json_ext = "'{ `"rule`": { $l_rules_json }'"
write-host("Actual json BODY:")
write-host($l_rules_json_ext)
$response_t = Invoke-Restmethod -Uri $api_uri_t -Method POST -Headers $headers -ContentType 'application/json' -UseBasicParsing -Body $l_rules_json_ext
}

How do I fix a "cannot bind parameter 'uri'. Cannot convert the...." when converting json in powershell?

I am doing a Get-Weather project in powershell, where I pull data down from weatherapi.com . I am able to successfully connect to the website using an API key but, when I try to convert it from json in the script it doesn't work. The error I get is:
"Cannot bind parameter 'Uri'. Cannot convert the..."
I have tried so many different ways to write this:
$response = Invoke-RestMethod -uri $url -Method Get -ResponseHeadersVariable r -StatusCodeVariable s
$weatherobject = ConvertFrom-Json $url
The request for the website is:
$url = Invoke-WebRequest "http://api.weatherapi.com/v1/forecast.json?key=$key&q=$location&days=$Days"
Any help would be very much apperciated, thank you!
The input of the ConvertFrom-Json cmdlet is a JSON object. Look at the document below for more information
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.1#description
$url = "http://api.weatherapi.com/v1/forecast.json?key=$key&q=$location&days=$Days"
$response = Invoke-RestMethod -uri $url -Method Get -ResponseHeadersVariable r -StatusCodeVariable s
$weatherobject = ConvertFrom-Json $response

Powershell json, includeFields

I am trying to request information from one of our APIs using JSON however there is a lot which needs to be filtered out.
According to our API documentation, we have an "IncludeFields" query. How can I make it so when the information is requested, only information with "CS505MA001" is returned instead of the 100s of objects I'm getting.
$CommcellInfo = Invoke-RestMethod -Method Get -Uri $URL -Headers #{ "X- Auth-Token" = $Global:AuthToken; "includeFields" = "CS505MA001" }
$Include_Query = #{"includeFields"="CS505MA001"}
$ConvertedInclude_Query = ConvertTo-Json $Include_Query
$CommcellInfo = Invoke-RestMethod -Method Get -Uri $URL -Headers #{ "X-Auth-Token" = $Global:AuthToken }
I am trying to only show the returned information which contains certain text, how would I go about achieving this?

Expand Multi-level Powershell nested hash tables from JSON api call

I am having an issue with a JSON API call using Powershell, that returns a multi-level nested array. Using the standard convertfrom-json & convertto-json doesn't give me the full results. I just get a ...
I have done a lot of research on this and found the following link on stack for expanding the nested hash tables, and this is about the best format that I have gotten. For reference, I am trying to insert employee records into SQL Server. I have a JSON function for doing so, and need to get the JSON response in the expanded format. There are some security aspects, that won't allow me to post the actual detail so I am trying to provide an example of some issues that I am having. Keep in mind the response is for 1 employee record out of hundreds overall, and in SQL will be one table with a row per employee.
$json1 = Invoke-webRequest -Uri $Workeruri -Certificate $cert -Headers $WorkerHeader | convertfrom-json
$workers = $json1.workers | select -property *
$workers | format-table Name, #{n='Value'; e={
if ($_.Value -is [Hashtable]) {
$ht = $_.Value
$a = $ht.keys | sort | % { '{0}={1}' -f $_, $ht[$_] }
'{{{0}}}' -f ($a -join ', ')
} else {
$_.Value
}
}}
$workers
I have also tried:
$workers | convertto-json
and
$workers = json1.workers | foreach-object {$_}
The data returned comes back like this:
associateOID : XXXXXXXXXXXXXX
workerID : #{idValue=XXXXXXX}
person : #{governmentIDs=System.Object[]; legalName=; birthDate=0000-00-00; legalAddress=; genderCode=; maritalStatusCode=; socialInsurancePrograms=System.Object[]; tobaccoUserIndicator=False; raceCode=; customFieldGroup=}
workerDates : #{originalHireDate=2015-03-09; terminationDate=2016-03-18}
workerStatus : #{statusCode=}
businessCommunication : #{emails=System.object[]}
workAssignments : {#{itemID=xxxxxx; occupationalclassification=System.Object[]; etc}}
I need it to come back with all of the columns on the left side, utilizing the "AssociateOID" as the key identifier for the individual. I have previously gotten the JSON response to come back completely expanded using this format but it wasn't working with the import into SQL Server or looking very nice like the Google Postman response:
$json1 = Invoke-webRequest -Uri $Workeruri -Certificate $cert -Headers $WorkerHeader | format-list -property *
You mean you want to get a JSON file that all objects/properties are expanded, right? Use the -Depth option of ConvertTo-Json to write a JSON file properly. Default value of -Depth option is 2.
$workers | ConvertTo-Json -Depth 100
Specify the appropriate depth according to your JSON files.