本帖最后由 caruko 于 2015-1-27 19:50 编辑
平时 经常使用curl+fiddler,进行一些操作..
也经常遇到服务器的JSON,一般遇到 返回 json 都是直接 findstr + for token 截取想要的数据。
今天突然萌生一个想法,批处理能否解析 JSON ? 考虑了一上午,感觉还是可行的。
下午 经历了 数个版本
1、token=1* 嵌套call 方案
2、层次标记方案
最终诞生了以下 代码,基本上解析 JSON是没有问题了,更深层次没有测试。- @echo off&setlocal ENABLEDELAYEDEXPANSION
- for /f "delims=" %%a in (json.js) do set #json=!#json!%%a
- set #json=!#json: =!
- set #json=!#json:"=!
- set #json=!#json:{= { !
- set #json=!#json:}= } !
- set #json=!#json:[= [ !
- set #json=!#json:]= ] !
- set "#prefix#="
- set /a #arr=-1,#lv=0
- for %%a in (!#json!) do (
- for /f "tokens=1 delims={}[]" %%K in ("%%~a") do (
- for /f "tokens=1,2 delims=:" %%A in ("%%~a") do (
- if "%%~A"=="%%~a" (
- if defined arr_!#lv! set /a #arr+=1&echo,!#prefix#![!#arr!]=%%A
- )
- if "%%~A:"=="%%~a" set #prefix#=!#prefix#!.%%A
- if not "%%~A"=="%%~a" if not "%%~A:"=="%%~a" echo,!#prefix#!.%%A=%%B
- )
- )
- if "%%~a"=="{" (
- if defined arr_!#lv! set /a #arr+=1
- setlocal
- if defined arr_!#lv! set #prefix#=!#prefix#![!#arr!]
- set /a #lv+=1
- )
- if "%%~a"=="}" (
- endlocal
- )
- if "%%~a"=="]" (
- endlocal
- )
- if "%%~a"=="[" (
- setlocal
- set /a #lv+=1,#arr=-1
- set arr_!#lv!= +
- )
- )
复制代码 提供测试JSON- {"result":[{"rank":1,"name":"super","sum":498700},{"rank":2,"name":"\u6c34\u997a","sum":498700},{"rank":3,"name":"admin","sum":498650},{"rank":4,"name":"\u9e23","sum":472850},{"rank":5,"name":"\u6842\u5c0f\u8d85","sum":320350},{"rank":6,"name":"\u5434","sum":169150},{"rank":7,"name":"\u67e0\u6aac","sum":154600},{"rank":8,"name":"\u817e\u5c0f\u4fca\u5b50","sum":153700},{"rank":9,"name":"chs","sum":44000},{"rank":10,"name":"\u5510\u971e","sum":36700}],"max":498700,"rank":1,"page":1,"success":true}
-
- {
- "name":"中国",
- "province":[
- {
- "name":"黑龙江",
- "cities":{
- "city":["哈尔滨","大庆"]
- }
- },
- {
- "name":"广东",
- "cities":{
- "city":["广州","深圳","珠海"]
- }
- },
- {
- "name":"台湾",
- "cities":{
- "city":["台北","高雄"]
- }
- },
- {
- "name":"新疆",
- "cities":{
- "city":["乌鲁木齐"]
- }
- }
- ]
- }
复制代码
|