首页 > 解决方案 > Powershell脚本从json文件中获取数据

问题描述

我需要从 json 文件中提取具有特定标题的数据并将其输出到 csv 文件

$data = (Get-Content "C:\Users\QVL6\Downloads\express-ordering-web- 
variables.json" | ConvertFrom-Json)

获取数据

 [PSCustomObject[]]$data = @(
    [PSCustomObject]@{
    Name = 'Name'
    Type = 'Type'
    Value = 'Value'
    Description = 'Description'
}

)

$path = C:\Users\QVL6\
$data | Select-Object -Property Name, Type, Value, Description | Export -Csv 
-Path .\data.csv -NoClobber -NoTypeInformation

json文件:

  {
  "Id": "variableset-Projects-174",
  "OwnerId": "Projects-174",
  "Version": 23,
  "Variables": [
    {
      "Id": "dfd06d9f-5ab5-0b40-bfed-d11cd0d90e62",
      "Name": "apiConfig:orderCommandUrl",
      "Value": "http://dev.order-service.local",
      "Description": null,
      "Scope": {
        "Environment": [
          "Environments-63"
        ]
      },
      "IsEditable": true,
      "Prompt": null,
      "Type": "String",
      "IsSensitive": false
    },
    {
      "Id": "252a19a0-4650-4920-7e66-39a80c1c49ec",
      "Name": "apiConfig:orderCommandUrl",
      "Value": "http://qa.order-service.local",
      "Description": null,
      "Scope": {
        "Environment": [
          "Environments-63",
          "Environments-64"
        ]
      },
      "IsEditable": true,
      "Prompt": null,
      "Type": "String",
      "IsSensitive": false
    },

我想提取名称字段中的所有值

标签: jsonpowershell

解决方案


Get-Content已经返回一个字符串,因此您可以将输出直接转换为 json。$data = 获取内容“C:\Users\myFile\Downloads\express-ordering-web-variables.json”| ConvertFrom-Json

该变量$data已经是一个对象,因此您不必再次将其转换为 csv。您可以直接选择所需的标头并将其导出为 csv。

$data = Get-Content "C:\Users\myFile\Downloads\express-ordering-web- 
variables.json" | ConvertFrom-Json

#get some random data
[PSCustomObject[]]$data = @(
    [PSCustomObject]@{
        H1 = 'Test'
        H2 = 'Test2'
    },
    [PSCustomObject]@{
        H1 = 'Test'
        H2 = 'Test2'
    }
)

$data | Select-Object -Property H1, H2 | Export-Csv -Path $Path -NoClobber -NoTypeInformation

推荐阅读