Pramod Yadav
Pramod Yadav

Reputation: 557

jq '.[]' doesnt give jsonObjects but rather give psobjects in powershell. How to solve this?

Taking an example from JQs official site, I am trying to parse the jsonArray in below example screenshot.

Parsing Json Array using jq

I am trying to get both jsonObjects, so that I can do something with them for my problem statement. However, when I try to do this in PowerShell using below code:

$inputJson = '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'

$items = $inputJson | jq '.[]'

I get not two $items objects but 8 $items psobjects. As seen in the second screenshot. enter image description here

Any pointers, on what changes I can make to get only two jsonObjects here?

Upvotes: 0

Views: 502

Answers (2)

js2010
js2010

Reputation: 27516

The question is confusing. All jq does is output strings. Powershell will make each line a new string array element. The only way I see it doing what you want, is with jq's --compact-output option, which outputs one object (to jq) per line. That seems to be the way that online example was run, anyway. But to powershell, these are two strings. They would be objects to powershell only after using convertfrom-json.

$items = $inputJson | jq '.[]' --compact-output
$items

{"name":"JSON","good":true}
{"name":"XML","good":false}

Upvotes: 3

Pramod Yadav
Pramod Yadav

Reputation: 557

Although still dont know how to do it with jq, here is another way of achieving what I wanted using Powershell.

$inputJson = '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]' | ConvertFrom-Json
write-host "`nNr of jsonObjects:"
write-host $inputJson.Length

write-host "`nfirst jsonObject:"
Write-Host $inputJson[0]

write-host "`njsonObjects value:"
$value = $inputJson[0] | ConvertTo-Json
Write-Host $value

Result is: Nr of jsonObjects: 2

first jsonObject: @{name=JSON; good=True}

jsonObjects value: { "name": "JSON", "good": true }

Upvotes: 1

Related Questions