使用批处理脚本从json文件中读取URL

时间:2015-11-17 10:43:40

标签: json batch-file batch-processing

我正在通过batchscript读取配置json文件并动态创建变量。

json文件的内容如下所示

{ 
"ApplicationId":"c2b925c2-e5c9-4534-b855-43534",
"ApplicationProcess":"453453-ca1c-4735-806a-45345",
"VersionComponentId":"4533-35d2-4f0c-bb7a-rtert",
"uDClientFolder":"/udclient/",
"FID":"myId",
"FAuthToken":"mypassword",
"uDeployUrl":"https://myurl:8445",
"outPutDir":"..\Binaries\_PublishedWebsites\OutPut",
}

读取变量的批处理脚本如下所示

for /f "tokens=1,2 delims=:, " %%a in (' find ":" ^< ".\%jsonConfigFile%" ') do (


   set a=%%~a: =%
   set b=%%~b: =%
   set "%%~a=%%~b"
)

我在这里遇到两个问题。 1.无法读取uDeployUrl,因为它包含://。我只获得了网址的https部分。 2.如果我的json在keyname之前包含空格     “应用程序”:“值” 然后变量名称也会在其名称中包含空格。那么如何从变量名

中删除起始空格

提前致谢。

2 个答案:

答案 0 :(得分:0)

首先,您的配置json文件无效。 “ outPutDir”对象值中的反斜杠需要转义。因此,有效的json将是:

{
  "ApplicationId": "c2b925c2-e5c9-4534-b855-43534",
  "ApplicationProcess": "453453-ca1c-4735-806a-45345",
  "VersionComponentId": "4533-35d2-4f0c-bb7a-rtert",
  "uDClientFolder": "/udclient/",
  "FID": "myId",
  "FAuthToken": "mypassword",
  "uDeployUrl": "https://myurl:8445",
  "outPutDir": "..\\Binaries\\_PublishedWebsites\\OutPut"
}

我建议使用适当的JSON解释器,例如Xidel

xidel -s config.json -e "$json() ! eval(x'{.}:=$json/{.}')[0]"
ApplicationId := c2b925c2-e5c9-4534-b855-43534
ApplicationProcess := 453453-ca1c-4735-806a-45345
VersionComponentId := 4533-35d2-4f0c-bb7a-rtert
uDClientFolder := /udclient/
FID := myId
FAuthToken := mypassword
uDeployUrl := https://myurl:8445
outPutDir := ..\Binaries\_PublishedWebsites\OutPut

Xidel打开“ config.json”。默认情况下,$json表示json的内容。 $json()包含对象所有属性的序列:

ApplicationId
ApplicationProcess
VersionComponentId
uDClientFolder
FID
FAuthToken
uDeployUrl
outPutDir

这些字符串被馈送到eval-function的(!)处,输出如上所示。

要实际批量导出这些变量:

FOR /F "delims=" %%A IN ('xidel -s config.json -e "$json() ! eval(x'{.}:=$json/{.}')[0]" --output-format^=cmd') DO %%A
SET ApplicationId=c2b925c2-e5c9-4534-b855-43534
SET ApplicationProcess=453453-ca1c-4735-806a-45345
SET VersionComponentId=4533-35d2-4f0c-bb7a-rtert
SET uDClientFolder=/udclient/
SET FID=myId
SET FAuthToken=mypassword
SET uDeployUrl=https://myurl:8445
SET outPutDir=..\Binaries\_PublishedWebsites\OutPut

答案 1 :(得分:-1)

for /f "tokens=1* delims=:" %%a in ('find ":" "%jsonConfigFile%"') do set "%%~a=%%~b
  • 使用tokens=1*:后的所有内容转换为%%b
  • 使用~前缀删除%%a中的周围引号和%%b
  • 的开头引号
  • 由于%%b中的最后一个引号后跟,,因此不会删除它,但我们只需将整个set赋值括在双引号中,前面加上一个双引号即可最后的作业将是例如set "uDeployUrl=https://myurl:8445", - 最后一个逗号将被忽略。
  • find的第二个参数是文件名,因此无需通过<使用输入重定向