[英]How to get data from JSON file with batch script and write the data into a text file?
我想批量从* .json文件获取数据到file.txt
。
我的JSON文件config.json
:
"nodes": [
{
"id": "item1",
"host": "${host:item1}",
"apps": [
{
"id": "value1",
"template_id": "value1"
},
{
"id": "value2",
"template_id": "value2",
},
我只想获取节点apps
id
元素的值value1
和value2
。 但是在我的脚本中使用命令find
的问题实际上是它读取id
和template_id
的值。
是否可以将值设为id
而不是template_id
?
我尝试了这个...仍然无法正常工作...
setlocal EnableDelayedExpansion
set c=0
for /f "tokens=2 delims=:, " %%a in (' find "id" ^< "config.json" ') do (
set /a c+=1
set val[!c!]=%%~a
)
for /L %%b in (1,1,!c!) do echo !val[%%b]!
之后,我真的不知道如何在我的文本文件中获取所有这些数据。
您不应将结构化信息视为纯文本。
例如,以片段的Valid JSON (RFC 4627)
版本为例:
{
"nodes":[
{
"id":"item1",
"host":"${host:item1}",
"apps":[
{
"id":"value1",
"template_id":"value1"
},
{
"id":"value2",
"template_id":"value2"
}
]
}]
}
并使用PowerShell的cmdlet ConvertFrom-Json
,很容易收到正确的ID值
PoSh> $Json = Get-Content .\config.json | ConvertFrom-Json
PoSh> $JSon.Nodes.Apps.id
value1
value2
与批处理文件标签一起成批讨论
@Echo off
Powershell -Nop -C "(Get-Content .\config.json|ConvertFrom-Json).Nodes.Apps.id" >file.txt
您可以尝试使用jsonextractor.bat
。 为了拥有有效的json,我使用了以下方法:
{
"nodes": [{
"id": "item1",
"host": "${host:item1}",
"apps": [{
"id": "value1",
"template_id": "value1"
},
{
"id": "value2",
"template_id": "value2"
}
]
}]
}
并获取值:
for /f "tokens=* delims=" %%a in ('jsonextractor.bat test.json "nodes[0].apps[0].id"') do (
set "first_id=%%~a"
)
echo %first_id%
请使用像Xidel这样的不错的JSON解析器来解析JSON!
xidel -s config.json -e "$json/(.//apps)()/id" # or in full: $json/(nodes)()/(apps)()/id
value1
value2
要将输出保存到文件:
xidel -s config.json -e "$json/(.//apps)()/id" > output.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.