convert string to hashtable

Welcome Forums General PowerShell Q&A convert string to hashtable

Viewing 6 reply threads
  • Author
    Posts
    • #271915
      Participant
      Topics: 27
      Replies: 42
      Points: 394
      Rank: Contributor

      hi all,

      given this string:

      $string = ‘”MachineId”: “09f5eb07f057a4499cc1bfafeff95ef0”, “SessionID”: “e489ef09-d1af-4bb1-afd4-37baee89c70c”, “GeoID”: 39, “Ver”: “0.0.0.0”, “C2RClientVer”: “0.0”, “ErrorCode”: 30041, “ErrorType”: “InvalidProductInConfigXml”, “AppVErrorSource”: “”, “ErrorMessage”: “InvalidProductInConfigXml (PerformMSITransitions::HandleStateAction MSI C2R SxS prereq is predicted to fail.)”, “ErrorDetails”: “”, “ContextData”: “OException has occurred.”‘

      how can i convert this to a hashtable?

      thank you!

    • #271918
      Participant
      Topics: 16
      Replies: 1855
      Points: 3,568
      Helping Hand
      Rank: Community Hero

      That appears to be JSON with the missing curly bracket {} wrapper, so you can append the brackets to the string. This is using a string format, which requires escaped brackets:

      This creates a PSObject:

      This will allow you to easily parse and get the information rather than manually converting it to a hashtable.

      • This reply was modified 2 weeks, 1 day ago by Rob Simmers.
    • #271924
      Participant
      Topics: 27
      Replies: 42
      Points: 394
      Rank: Contributor

      wow!

      thank you very much!

    • #271927
      Participant
      Topics: 5
      Replies: 170
      Points: 656
      Helping Hand
      Rank: Major Contributor

      Here’s how I would tackle it.

       

    • #271930
      Participant
      Topics: 5
      Replies: 170
      Points: 656
      Helping Hand
      Rank: Major Contributor

      Definitely go with Rob’s solution.  I didn’t recognize it was JSON.  Fun exercise though 🙂

    • #273810
      Participant
      Topics: 6
      Replies: 5
      Points: 36
      Rank: Member

      Definitely go with Rob’s solution. I didn’t recognize it was JSON. Fun exercise though 🙂

      Thanks for that breakdown.  I’ve been half-heartedly giving up on trying to convert text strings, CSV’s, returned objects to hashtables, but this looks like a good springboard for me!  Cheers!

      Patrick

    • #273855
      Participant
      Topics: 9
      Replies: 676
      Points: 2,674
      Helping Hand
      Rank: Community Hero

      Here is another approach

      And if you wanted to make it a PSCustomObject

Viewing 6 reply threads
  • You must be logged in to reply to this topic.