Parse simple JSON string in Batch

后端 未结 5 1892
执笔经年
执笔经年 2020-12-16 00:36

How do you parse a simple JSON string in Batch?

For example, if I have the following JSON string:

{ \"...\":\"...\", \"year\": 2016, \"time\": \"05:01\

5条回答
  •  感动是毒
    2020-12-16 01:01

    @echo off
    setlocal
    
    set string={ "other": 1234, "year": 2016, "value": "str", "time": "05:01" }
    
    rem Remove quotes
    set string=%string:"=%
    rem Remove braces
    set "string=%string:~2,-2%"
    rem Change colon+space by equal-sign
    set "string=%string:: ==%"
    rem Separate parts at comma into individual assignments
    set "%string:, =" & set "%"
    
    echo other="%other%"
    echo year="%year%"
    echo value="%value%"
    echo time="%time%"
    

    Output:

    other="1234"
    year="2016"
    value="str"
    time="05:01"
    

    A small inconvenient of this method is that "time" Batch dynamic variable will be replaced by the new JSON one, but if you use setlocal command, this point don't cause any problem.

    EDIT: Just to complete cz3ch's request of put results into "string" array instead of placing them inside individual variables:

    @echo off
    setlocal
    
    set string={ "other": 1234, "year": 2016, "value": "str", "time": "05:01" }
    
    rem Remove quotes
    set string=%string:"=%
    rem Remove braces
    set "string=%string:~2,-2%"
    rem Change colon+space by "]equal-sign"
    set "string=%string:: =]=%"
    rem Separate parts at comma into individual array assignments
    set "string[%string:, =" & set "string[%"
    
    set string[
    

提交回复
热议问题