批量解析简单的JSON字符串 [英] Parse simple JSON string in Batch
问题描述
如何在批处理中解析一个简单的JSON字符串?
How do you parse a simple JSON string in Batch?
例如,如果我具有以下JSON字符串:
For example, if I have the following JSON string:
{ "...":"...", 年":2016年, "time":"05:01", "...":"...", }
{ "...":"...", "year": 2016, "time": "05:01", "...":"...", }
此JSON字符串包含许多元素,其中两个是年"和时间".我想从该字符串中提取两个变量中"year"和"time"的值,而不使用任何外部库(即,我不想为此安装下载任何外部实用程序,新安装的Windows应该具有所有必要的工具来做到这一点.
This JSON string has a number of elements and two of them are "year" and "time". From this string, I want to extract the values for "year" and "time" in two variables without using any external libraries (i.e., I don't want to install download any external utils for this, a freshly installed Windows should have all the necessary tools to do this).
推荐答案
这里是Batch + PowerShell的混合解决方案. PowerShell将JSON文本对象化(反序列化),并以key = value格式输出,以供捕获并通过批处理for /f
循环设置为批处理变量.用.bat扩展名保存并尝试一下.
Here's a hybrid Batch + PowerShell solution. The PowerShell objectifies (deserializes) the JSON text and outputs it in key=value format to be captured and set as batch variables by the batch for /f
loop. Save this with a .bat extension and give it a shot.
<# : 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]%
.
Then if you want only the year and time values, just use %JSON[year]%
or %JSON[time]%
.
如果您正在从.json文件中读取JSON,则可以让PowerShell部分读取该文件,将($env:JSON)
替换为((gc jsonfile.json))
.然后,您将完全不必依赖JSON是多行的,美化的还是缩小的JSON.两种方式都将反序列化.
If you're reading your JSON from a .json file, you could have the PowerShell portion read the file, replacing ($env:JSON)
with ((gc jsonfile.json))
. Then you wouldn't be dependent at all on whether your JSON is multi-line and beautified or minified. It'll be deserialized all the same either way.
如果需要考虑执行速度,则您可能更喜欢Batch + JScript混合解决方案.它可以将JSON反序列化为与PowerShell解决方案相同的对象,但是从Batch上下文调用JScript比从Batch调用PowerShell命令或脚本更快.
If execution speed is a concern, you might prefer a Batch + JScript hybrid solution. It deserializes the JSON into an object the same as the PowerShell solution, but invoking JScript from a Batch context is faster than invoking a PowerShell command or script from Batch.
@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()
方法).
And as is the case with the first PowerShell hybrid solution, you can parse multi-line JSON by reading the .json file from within the JScript portion if you wish (by creating a Scripting.FileSystemObject
object and calling its .OpenTextFile()
and .ReadAll()
methods).
这是另一种纯批处理解决方案,但该解决方案将键=值对设置为关联数组,以避免像Aacini的解决方案那样踩踏%time%
.我确实认为,最好将JSON解析为辅助语言中的对象,而不是纯批处理中的纯文本,但我也意识到,最佳答案并不总是最受欢迎.
Here's another pure batch solution, but one which sets key=value pairs as an associative array to avoid stomping on %time%
as Aacini's solution does. I really think it's better to parse JSON as an object in a helper language rather than as flat text in pure batch, but I also realize that the best answer is not always the most popular.
@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[
这篇关于批量解析简单的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!