Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a JSON object to a file using Powershell?

I have converted the following JSON file to powershell representation object.

{
"computer": [
    {
        "children": [   
            {   
                "children": [ {
                   "children": [ {
                        "path": "T:\Dropbox\kvaki.html",
                        "name": "kvaki",
                        "type": "url",
                        "url": "http://example.com"
                   } ],
                    "path": "T:\Dropbox\",
                    "name": "Njusha",
                    "type": "folder"
                }, {
                    "path": "T:\Dropbox\Europa.html",
                    "name": "Europa",
                    "type": "url",
                    "url": "http://example.com"
                }, {
                    "path": "T:\Dropbox\math.html",
                    "name": "math",
                    "type": "url",
                    "url": "http://example.com"
                } ],
                "path": "T:\Dropbox\",
                "name": "Money",
                "type": "folder"
            }
        ],
        "full_path_on_file_sys": "T:\Dropbox\"
    }
]

}

After doing some computations with powershell representation I would like to save it to file as JSON. But command $jsonRepresentation | ConvertTo-Json | Out-File "D:\dummy_path\file.json" saves it in this way

{
    "computer":  [
                     {
                         "children":  " ",
                         "full_path_on_file_sys":  "T:\Dropbox\"
                     }
                 ]
}

Question: how to achieve correct saving of complex powershell JSON representation?

like image 401
Puzik Avatar asked Mar 08 '14 22:03

Puzik


People also ask

How do I save a JSON object to a JSON file?

To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS's writeFile() function.

How do I get JSON data in PowerShell?

One way to query an API with PowerShell and get some JSON in return is to use the Invoke-WebRequest cmdlet. This cmdlet can query any web service/site over HTTP and return information (not just JSON).


4 Answers

-depth argument for ConvertTo-Json solves the issue.

$jsonRepresentation | ConvertTo-Json -depth 100 | Out-File "D:\dummy_path\file.json"
like image 109
Puzik Avatar answered Oct 19 '22 22:10

Puzik


Just pipe it to Set-Content, or Out-File:

Get-Process powershell |
 ConvertTo-Json | 
 Set-Content json.txt
like image 24
mjolinor Avatar answered Oct 19 '22 20:10

mjolinor


If you want to both view the output and save it to file, you can pipe the tee command.

Get-Process powershell | ConvertTo-Json |  Tee-Object json.txt
like image 4
Jim Wolff Avatar answered Oct 19 '22 22:10

Jim Wolff


$json.properties.metadata | ConvertTo-Json -Compress
like image 2
Peter Avatar answered Oct 19 '22 20:10

Peter