如何使用批处理脚本替换JSON文件中的环境变量?

问题描述 投票:0回答:1

我正在尝试将以下文件中的环境变量替换为其各自的值:

一些.json:

{
    "verion": 3,
    "name": "some name",
    "description": "some description",
    "api_key": "%API_KEY%"
}

这是我正在使用的批处理脚本:

@echo off
setlocal enabledelayedexpansion

set "target_file=some.json"
set "output_file=output.json"
set "API_KEY=12345"

goto:start

:expand
echo %~1 >> %output_file%
goto:eof

:start
echo. > %output_file%
for /f "delims=" %%i in (%target_file%) do call:expand "%%i"

运行此程序时,output.json 正是:


{ 
    "verion": 3, 
    "api_key": "12345" 
} 

为什么它跳过 some.json 的第 3 行和第 4 行?难道不应该输出some.json的所有行吗?

json batch-file dos
1个回答
0
投票

因为这些行的内容有引号,并且您将

%%i
括在引号中,这实际上改变了哪些是开引号,哪些是闭引号。现在,
:expand
认为数据看起来像这样:

"{"
"    "verion": 3,"
"    "name": "some name","
"    "description": "some description","
"    "api_key": "12345""
"}"

标记化规则此时变得很奇怪,但基本上,在发生偶数个引号后,该行会在空格上分开。这意味着对于

name
行,
"    "name": "some
是整个第一个标记。

"    "name": "some
|    |    | ||    |
|    |    | ||    This is the first actual space outside of quotes, so we tokenize here
|    |    | ||
|    |    | ||
|    |    | |Now there are an even number of quotes again
|    |    | |
|    |    | |
|    |    | So this space is technically inside of quotes
|    |    |
|    |    |
|    |    There are now three quotes
|    |
|    |
|    This is a close quote but there's no space after it so we keep reading
|  
The opening quote

由于解释器认为有多个标记,因此您可以使用

%*
来获取整行。

@echo off
setlocal enabledelayedexpansion

set "target_file=some.json"
set "output_file=output.json"
set "API_KEY=12345"

goto:start

:expand
echo %* >> %output_file%
goto:eof

:start
echo. > %output_file%
for /f "delims=" %%i in (%target_file%) do call :expand %%i
© www.soinside.com 2019 - 2024. All rights reserved.