1

How do we convert the json string into a hastable? .

Suppose I have a string such as:

{"Application":"Billing Interface","Business Area":"Interfaces","Region":"YO"}

How do we convert this to a hash table?

I'm doing this right now:

$myJsonString= 
$myJsonString.TrimEnd("}")
             .TrimStart("{")
             .Replace('":"',"= ")
             .Replace('"',"")
             .Replace(","," `n ")
$myJsonString = ConvertFrom-StringData -StringData $myJsonString

How do we convert the json string into a hastable?

3 Answers 3

2

I am not sure why you need a Hashtable specifically, but you could use ConvertFrom-Json to output a PSCustomObject and then convert to a hash table ($hash).

$myjsonstring = '{"Application":"Billing Interface","Business Area":"Interfaces","Region":"YO"}'
$myjsonstring | ConvertFrom-Json | Foreach-Object {
    $hash = @{}
    $_.PSObject.Properties | Foreach-Object {
        $hash.Add($_.Name,$_.Value)
    }
    $hash
}

Note that PowerShell Core has the -AsHashTable parameter that may work for you if you are running that version.

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

Comments

1

If you take that json string you have, convert it to an object, you can access the elements by using the name of the element.

$JsonString = "{""Application"":""Billing Interface"",""Business Area"":""Interfaces"",""Region"":""YO""}"
#OR 
$JsonString = Get-Content fromFile.txt

$object = $JsonString | ConvertFrom-Json

$object.Application
$object.'Business Area'

Microsoft Docs on ConvertFrom-Json

Comments

1

An easiest way to do this using .NET class System.Web.Script.Serialization.JavaScriptSerializer . Microsoft Docs Link: https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

Add-Type -AssemblyName "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
$jsSerializer = New-Object -TypeName System.Web.Script.Serialization.JavaScriptSerializer
$jsSerializer.Deserialize($myjsonstring, 'Hashtable')

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.