itzik Paz itzik Paz - 3 months ago 18
PowerShell Question

Convert string to Json with powershell

I have a text file with rows like :

TRACE 2016-06-23 08:47:54,803 {"x":"0.0000179000","l":"Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.34209)","a":"Get","p":"345","u":"dae824a6-144b-4135-a6fd-01584f06a27f","i":"10.0.2.166","s":"US","e":"start"}


It will be great if someone can help how to convert it to JSON with powershell (I tried it with ConvertTo-JSON , but without success.)

Answer

It is not entirely clear what you want. If you want a valid JSON string then just remove the first part of the string (this part: TRACE 2016-06-23 08:47:54,803) and your done:

$data = 'TRACE 2016-06-23 08:47:54,803 {"x":"0.0000179000","l":"Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.34209)","a":"Get","p":"345","u":"dae824a6-144b-4135-a6fd-01584f06a27f","i":"10.0.2.166","s":"US","e":"start"}'

$json = $data.Substring($data.IndexOf("{"))

If you want to convert it from JSON to an object then you still need to convert the string into a valid JSON string and then you can simply do this:

$myObject = ConvertFrom-Json $json
Comments