Passing arguments with spaces in it to a subroutine

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Reino
Posts: 17
Joined: 14 May 2015 06:13
Contact:

Passing arguments with spaces in it to a subroutine

#1 Post by Reino » 13 Jul 2019 04:24

Hello,

I'm working with JSONs and I'm having trouble correctly passing these JSONs as arguments with spaces in it to a subroutine.
The following simple JSON, {"a": 1, "b": 2}, is working fine:

Code: Select all

SET json={^^^"a^^^": 1^^^, ^^^"b^^^": 2}

SETLOCAL ENABLEDELAYEDEXPANSION
CALL :Info "!json!"
ENDLOCAL
EXIT /B 0

:Info
ECHO %~1
EXIT /B
Output:

Code: Select all

{^"a^": 1^, ^"b^": 2}
So despite there being spaces between the attribute and value, this is no problem it seems.

The following simple JSON with spaces in the attribute's values, {"a": "a b c", "b": "x y z"}, is NOT working correctly:

Code: Select all

SET json={^^^"a^^^": ^^^"a b c^^^"^^^, ^^^"b^^^": ^^^"x y z^^^"}

SETLOCAL ENABLEDELAYEDEXPANSION
CALL :Info "!json!"
ENDLOCAL
EXIT /B 0

:Info
ECHO %~1
EXIT /B
Output:

Code: Select all

{^"a^": ^"a
Where as the expected/desired output was:

Code: Select all

{^"a^": ^"a b c^"^, ^"b^": ^"x y z^"}
I have also looked at ECHO %* which results in:

Code: Select all

"{^^"a": ^"a b c^"^, ^"b^": ^"x y z^"}"
It first of all quotes the entire string (sadly %~* doesn't work) and then strangely enough escapes only the first escape-character ( ^ ) and removes the second, but leaves the rest intact...

Does anyone know how I can have my script output the expected/desired output as shown above?

jeb
Expert
Posts: 907
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Passing arguments with spaces in it to a subroutine

#2 Post by jeb » 13 Jul 2019 05:17

Your problem is, that the spaces are outside of quotes, because of doble quoting

call :info "!json!" -> call :info "{^"a^": ^"a b c^"^, ^"b^": ^"x y z^"}"

Only the red text is inside qotes, the rest is outside and the spaces are used as delimiters.

You could solve that with carets in front of some of the quotes, but that would be messy.

It's much simlper to transfer not the content to %1, instead transfer only the variable name!

Code: Select all

call :info json

:info
set "content=!%1!"
echo !content!

Reino
Posts: 17
Joined: 14 May 2015 06:13
Contact:

Re: Passing arguments with spaces in it to a subroutine

#3 Post by Reino » 13 Jul 2019 05:45

Thanks a lot for your input, jeb! Passing the variable name as argument is something I would've never come up with.

Code: Select all

SET json={^^^"a^^^": ^^^"a b c^^^"^^^, ^^^"b^^^": ^^^"x y z^^^"}

SETLOCAL ENABLEDELAYEDEXPANSION
CALL :Info json
ENDLOCAL
EXIT /B 0

:Info
ECHO !%1!
EXIT /B
Output:

Code: Select all

{^"a^": ^"a b c^"^, ^"b^": ^"x y z^"}

Post Reply