使用分隔符以字符串形式从json文件中获取值

时间:2018-07-19 09:38:15

标签: json api powershell github

我有一个具有以下格式的json文件:

{
"total_count":  57,
"incomplete_results":  false,
"items":  [
              {
                  "id":  123456,
                  "node_id":  "dfghdfjfgjftgjhtfyjh",
                  "name":  "Firstrepo",
                  "full_name":  "MyOrganization/Firstrepo",
[SKIP]
              },
              {
                  "id":  4756758,
                  "node_id":  "dtghtfjgjyuj",
                  "name":  "Secondrepo",
                  "full_name":  "MyOrganization/Secondrepo",
[SKIP]
              },
              {
                  "id":  568578567,
                  "node_id":  "dsgdfghftghtfyjtyj",
                  "name":  "Anotherrepo",
                  "full_name":  "MyOrganization/Anotherrepo",
[SKIP]
              },
              {
                  "id":  58567856,
                  "node_id":  "sjdhfbgsdjfgjsdfjjs",
                  "name":  "Somerepo",
                  "full_name":  "MyOrganization/Somerepo",
[SKIP]
              },

如何获取存储库的值并将它们以csv格式写入变量或文件中。喜欢:

Firstrepo,Secondrepo,Anotherrepo,Somerepo

获取值的脚本: 配置来自Github的回购清单

$GithubAPIURL = "https://api.github.com"
$Suffix = "/search/repositories"
$Additions = "?q=org:MYORG:SEARCH&page=1&per_page=100" 
$GithubAPIToken = "&access_token=MYTOKEN" 

过程

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$variable = ((Invoke-Webrequest $GithubAPIURL$Suffix$Additions$GithubAPIToken).content | ConvertFrom-Json)
$jsonfile = "c:\a\test.json"
$variable | ConvertTo-Json | Out-File $jsonfile -Encoding UTF8

获取名称列表

$Reponames = (Get-Content $jsonfile -Encoding UTF8 | ConvertFrom-Json)   

1 个答案:

答案 0 :(得分:2)

要获取存储库名称,请使用:

(Get-Content $jsonfile -Encoding UTF8 | ConvertFrom-Json).items.name

要将其转换为.csv文件:

(Get-Content $jsonfile -Encoding UTF8 | ConvertFrom-Json).items | ConvertTo-Csv -Delimiter ';' -NoTypeInformation | Out-File $csvFilePath