Skip to content

Instantly share code, notes, and snippets.

@navono
Last active June 10, 2024 03:28
Show Gist options
  • Save navono/992727c277bf3478a06540963f48f7e9 to your computer and use it in GitHub Desktop.
Save navono/992727c277bf3478a06540963f48f7e9 to your computer and use it in GitHub Desktop.
parse JSON file by windows batch
:: Read file "package.json" into variable string, removing line breaks.
set string=
for /f "delims=" %%x in (package.json) do set "string=!string!%%x"
rem Remove quotes
set string=%string:"=%
rem Remove braces
set "string=%string:~2,-2%"
rem Change colon+space by equal-sign
set "string=%string:: ==%"
rem Separate parts at comma into individual assignments
set "%string:, =" & set "%"
echo %version%
@TriHydera
Copy link

Great example

@Ximaz
Copy link

Ximaz commented Apr 18, 2021

Is this code able do to :

@REM prints out the 'test' command executed by node :
echo %scripts[test]%

@navono
Copy link
Author

navono commented Apr 19, 2021

You can try it.

@TriHydera
Copy link

What about with a http request that gets json?

@Ximaz
Copy link

Ximaz commented Apr 9, 2022

What about with a http request that gets json?

Well, even though you get JSON as response, the Batch language has to understand it and interpret it. That's what we are asking for, because you can't treat a large amount of data with this method.

@TriHydera
Copy link

Just a dumb question, where is %version% defined in the script?

@Ximaz
Copy link

Ximaz commented Apr 9, 2022

Just a dumb question, where is %version% defined in the script?

Let's suppose this is the package.json file the script tries to read :

{
 ...
 "version": "1.0.0",
 ...
}

Then Batch will take the key version from the JSON file as a new variable, which value is the version value linked into the JSON file. That's why you can't use this for huge objects such as this one :

{
 ...
 "version": {
    "debug": "1.0.0",
    "production": "1.0.1"
 },
 ...
}

You would not be able to get the debug and production value using version as key.

@jkearins
Copy link

jkearins commented Mar 8, 2023

Nice code. Sample of package.json:

{ "dummy": "invisible", "dbpath": "c:\tmp", "dbname": "hidra" }

Some limitations:

  • Spaces after first '{' and before last '}' are needed
  • No spaces in keys and in values
    "msg": "Hi all" <-- prohibited
  • One space is necessary after ':'
  • First key:value pair is allways unreachable
echo dummy=%dummy%
echo dbpath=%dbpath%
echo dbname=%dbname%

output:

dummy=
dbpath=c:\tmp
dbname=hidra

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment