batch-file - 批量解析简单的 JSON 字符串

标签 batch-file

如何在 Batch 中解析简单的 JSON 字符串?

例如,如果我有以下 JSON 字符串:

{ "...":"...", “年份”:2016年, “时间”:“05:01”, "...":"...", }

这个 JSON 字符串有许多元素,其中两个是“年份”和“时间”。从这个字符串中,我想在两个变量中提取“年份”和“时间”的值,而不使用任何外部库(即,我不想为此安装下载任何外部实用程序,新安装的 Windows 应该拥有所有执行此操作所需的工具)。

最佳答案

这是一个混合 Batch + PowerShell 解决方案。 PowerShell 对象化(反序列化)JSON 文本,并以 key=value 格式输出,以便通过批处理 for/f 循环捕获并设置为批处理变量。使用 .bat 扩展名保存并尝试一下。

<# : batch portion (contained within a PowerShell multi-line comment)
@echo off & setlocal

set "JSON={ "year": 2016, "time": "05:01" }"

rem # re-eval self with PowerShell and capture results
for /f "delims=" %%I in ('powershell "iex (${%~f0} | out-string)"') do set "%%~I"

rem # output captured results
set JSON[

rem # end main runtime
goto :EOF

: end batch / begin PowerShell hybrid code #>

add-type -AssemblyName System.Web.Extensions
$JSON = new-object Web.Script.Serialization.JavaScriptSerializer
$obj = $JSON.DeserializeObject($env:JSON)

# output object in key=value format to be captured by Batch "for /f" loop
foreach ($key in $obj.keys) { "JSON[{0}]={1}" -f $key, $obj[$key] }

如果您只需要年份和时间值,只需使用 %JSON[year]%%JSON[time]%

如果您从 .json 文件读取 JSON,则可以让 PowerShell 部分读取该文件,并将 ($env:JSON) 替换为 ((gc jsonfile.json ))。那么你就根本不需要依赖你的 JSON 是多行的、美化的还是缩小的。无论哪种方式,它都会被反序列化。

<小时/>

如果执行速度是一个问题,您可能更喜欢 Batch + JScript 混合解决方案。它将 JSON 反序列化为与 PowerShell 解决方案相同的对象,但从 Batch 上下文调用 JScript 比从 Batch 调用 PowerShell 命令或脚本更快。

@if (@CodeSection == @Batch) @then
@echo off & setlocal

set "JSON={ "year": 2016, "time": "05:01" }"

rem // re-eval self with JScript interpreter and capture results
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0"') do set "%%~I"

rem // output captured results
set JSON[

rem // end main runtime
goto :EOF

@end // end Batch / begin JScript hybrid code

var htmlfile = WSH.CreateObject('htmlfile'),
    txt = WSH.CreateObject('Wscript.Shell').Environment('process').Item('JSON');

htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
var obj = htmlfile.parentWindow.JSON.parse(txt);
htmlfile.close();

for (var i in obj) WSH.Echo('JSON[' + i + ']=' + obj[i]);

与第一个 PowerShell 混合解决方案的情况一样,如果您愿意,您可以通过从 JScript 部分中读取 .json 文件来解析多行 JSON(通过创建 Scripting.FileSystemObject对象并调用其 .OpenTextFile().ReadAll() 方法)。

<小时/>

这是另一种纯批处理解决方案,但它将 key=value 对设置为关联数组,以避免像 Aacini 的解决方案那样对 %time% 造成影响。我确实认为将 JSON 解析为辅助语言中的对象而不是纯批处理中的平面文本更好,但我也意识到最好的答案并不总是最受欢迎的。

@echo off
setlocal

set "JSON={ "other": 1234, "year": 2016, "value": "str", "time": "05:01" }"

set "JSON=%JSON:~1,-1%"
set "JSON=%JSON:":=",%"

set mod=0
for %%I in (%JSON%) do (
    set /a mod = !mod
    setlocal enabledelayedexpansion
    if !mod! equ 0 (
        for %%# in ("!var!") do endlocal & set "JSON[%%~#]=%%~I"
    ) else (
        endlocal & set "var=%%~I"
    )
)

set JSON[

关于batch-file - 批量解析简单的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374496/

相关文章:

batch-file - 批量更改颜色的代码 : How is it working?

windows - 根据参数创建函数

batch-processing - 如何检查用户输入是否以批处理(.bat)脚本中的特定字符串结尾

windows - 如果不成功则暂停命令而不是自动关闭

html - 如何使用批处理文件在 HTML 文件中写入 "greater than symbol"

windows - 批处理文件 : Is it possible to extract a substring where the index is a variable?

git - 在批处理脚本中使用 git 命令时,如何因错误而失败?

batch-file - reg 查询后管道不起作用?

windows - 如何防止批处理文件(.bat)在运行命令时关闭终端?

windows - 如何获取windows批处理的父文件夹