2016-05-04 5 views
1

Я использую powershell для Windows 10. Мне нужно сохранить json-файл в формате отпечатанного отпечатка. Я пробовал различные комбинации кода ниже без везения.Сохранение JSON в файл с красивой печатью с помощью Powershell

$url = example.com/api/someThingy $saveAs = people.json Invoke-RestMethod -Uri $url -Method Get -OutFile $saveAs;

JSON Sample (Существует вероятность того, что я снял то, что делает разницу.)

{"id":"123456","name":"Lorem", "content":null,"purpose":"<p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>\n<p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>","when":"<ul>\n<li>Sed ut perspiciatis unde omnis iste natus error sit voluptatem</li>\n</ul>","Purpose":"<p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>\n<p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>"}

ответ

1

Попробуйте ниже:

$url = example.com/api/people 
$saveAs = people.json 
$jsonContent = Invoke-RestMethod -Uri $url -Method Get; 

$prettyJsonContent = ($jsonContent | ConvertFrom-Json | ConvertTo-Json) 

$prettyJsonContent *> $saveAs 

выше фрагмент кода использует PowerShell's ConvertFrom-Json и ConvertTo-Json, чтобы вставить JSON в красивую печать , Затем последняя строка просто печатает содержимое JSON для имен файлов как $saveAs в текущем каталоге.

+0

У меня были проблемы с дублирующими ключевыми именами с этим решением. Опять же, не представленный в моем примере выше. –

+1

Ну, тогда вам нужно исправить образец. Одно дело - удалить конфиденциальную информацию, но мы должны иметь возможность воспроизвести проблему. –

+0

Прошу прощения, я думаю, что некоторые из важных данных - моя проблема. –

2

Вы можете использовать ConvertTo-Json и сохранить это. Ex.

$url = "example.com/api/people" 
$saveAs = people.json 

Invoke-RestMethod -Uri $url -Method Get | 
ConvertTo-Json | 
Set-Content $saveAs 

Образец:

Invoke-RestMethod -Uri "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo" | 
ConvertTo-Json | 
Set-Content .\test.txt 
+0

Это работало для меня в прошлом, но почему-то в этом случае оно не работает. –

+0

Что значит не работает? Такой же результат, как '-outfile'? –

+0

Сохраняет, но не красиво окрашивает. –

0

Запуск через Json.NET сделал трюк.

$newtonSoftPath = "c:\mycode\packages\Newtonsoft.Json.8.0.3\lib\net40\Newtonsoft.Json.dll"; 
[System.Reflection.Assembly]::LoadFile($newtonSoftPath); 

$url = "example.com/api/people" 
$saveAs = "people.json"; 

$result = Invoke-WebRequest -Uri $url -Method Get; 
#for json array 
#$json = [Newtonsoft.Json.Linq.JArray]::Parse($result); 

$json = [Newtonsoft.Json.Linq.JObject]::Parse($result); 
$json.ToString() | Out-File $saveAs; 
Смежные вопросы