更改.json文件中的值

时间:2015-07-27 23:41:48

标签: batch-file

我有一个简单的问题。 我有一个带有以下内容的config.json文件

"DefaultAdminUsername": "Administrator@test.com",
"DefaultAdminPassword": "Admin!",
"DefaultNoOfUsers": "100",

我想修改" DefaultNoOfUsers"的值。从批处理文件 例如:从100更改为1000

伪代码可以是

for /f %%A in (config.json) do (

    SET key = value
)

echo %VERSION%
echo %TEST%

1 个答案:

答案 0 :(得分:1)

这是一个有点评论的批处理文件,用于在文件config.json中进行此替换而不检查输入错误。

@echo off
rem Exit this batch file if file config.json does not exist in current directory.
if not exist config.json goto :EOF

rem Make sure that the temporary file used does not exist already.
del "%TEMP%\config.json" 2>nul

rem Define a default value for number of users.
set "DefaultNoOfUsers=100"

rem Ask user of batch file for the number of users.
set /P "DefaultNoOfUsers=Number of users (%DefaultNoOfUsers%): "

rem Copy each line from file config.json into temporary file
rem with replacing on line with "DefaultNoOfUsers" the number.
for /F "tokens=1* delims=:" %%A in (config.json) do (
    if /I %%A == "DefaultNoOfUsers" (
        echo %%A: "%DefaultNoOfUsers%",>>"%TEMP%\config.json"
    ) else (
        echo %%A:%%B>>"%TEMP%\config.json"
    )
)

rem Move the temporary file over file config.json in current directory.
move /Y "%TEMP%\config.json" config.json >nul

rem Delete the used environment variable.
set "DefaultNoOfUsers="

在命令提示符窗口for /?中运行并阅读窗口中的整个帮助输出,以了解 for 循环的工作原理。