0

I have the below JSON variable in Powershell and want to loop through each array to return the total value only. For example, I would expect $response2.results.daily[0], ...daily[1] ... etc would allow me to access each array in the array but it seems i have to declare the specific array name ex '2020-05-10'?

Is there a better way to handle APIs through PS?

enter image description here

2
  • 1
    There definitely is a way to improve the response from that API, so it's easier to handle. Don't use an object ({daily: {"5/10/2020": {"total": "$0.030"}}}), Use an array ({daily: [{date: "2020-05-10", "total": "$0.030"}, ...]}). Changing the data layout will make your life easier on more than one front, if you have any control over the API. Commented May 10, 2020 at 21:43
  • This comes up a lot: stackoverflow.com/questions/33520699/… Commented May 11, 2020 at 2:05

1 Answer 1

2

You can use the hidden psobject property to obtain the individual property names on the $response2.results.daily object, then use those to access each array:

# use psobject to enumerate the property names (ie. '5/10/2020')
$dates = $response2.results.daily.psobject.Properties.Name

# loop through the property names
$dailyStats = $dates |ForEach-Object {
  $date = $_
  # Add the name (= date) as a new "date" property to the object
  $response2.results.daily.$name |Select-Object @{Name='date';Expression={$name}},*
}

$dailyStats will now be an array of objects like:

date      total   sms-in sms-out suppress
----      -----   ------ ------- --------
5/10/2020 $31.770 102    2,016   1
5/9/2020  $0.060  4      0       0
etc...

Is there a better way to handle APIs through PS?

No idea, given that we don't know how you obtained the response in the first place ¯\_(ツ)_/¯

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.