json - 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
},
我想提取名称字段中的所有值
解决方案
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
推荐阅读
- python - 如何在 TwisterOS/Debian 上安装 pygame 的扩展映像模块?
- regex - 当换行符位于字符串末尾时,正则表达式不起作用
- r - 将多个排他二元变量(列)合并到一个单因子列中
- mysql - 为什么我的中间端节点服务器在连接到数据库后停止运行
- javascript - 赛普拉斯:如何处理从 iframe 触发的窗口确认关闭
- python - 为基于 NaN 的列创建 IF 语句
- c++ - 线程安全的“漂亮计数器”(又名“施瓦茨计数器”)
- javascript - React - 将值传递给 setState 回调
- excel - VBA 宏 - 打开工作簿,设置活动,删除列
- ansible - Ansible:Blockinfile 对它可以创建的文件大小有限制吗?