Search code examples
jsonbatch-filebatch-processing

Reading URL from json file by using batch script


I am reading a config json file through batchscript and creating variables dynamically.

Content of json file is given below

{ 
"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",
}

Batch script to read variables is given below

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


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

Here i am facing two problems. 1. Unable to read uDeployUrl because it contains ://. I am getting only https part of the url. 2. If my json contains space before the keyname like "Application":"value" Then variable name will also contain space in it's name. So how can i remove starting space from variable name

Thanks in advance.


Solution

  • for /f "tokens=1* delims=:" %%a in ('find ":" "%jsonConfigFile%"') do set "%%~a=%%~b
    
    • Use tokens=1* to get everything after : into %%b
    • Use ~ prefix to strip the surrounding quotes from %%a and the opening quote from %%b
    • Since the last quote in %%b is followed by , it won't be removed but we can simply enclose the entire set assignment into doublequotes by prefixing it with one doublequote so that the final assignment will be for example set "uDeployUrl=https://myurl:8445", - the last comma will be ignored.
    • find's second parameter is a file name so no need to use input redirection via <