-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGUI4ExcelToJson.ahk
599 lines (570 loc) · 26.6 KB
/
GUI4ExcelToJson.ahk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
; 这是一个为ExcelToJson编写的可视化UI,整合了错误日志打印、可视化进度、目录和配置管理等功能
#NoTrayIcon
#NoEnv
#SingleInstance, Force
SetBatchLines, -1
SetWorkingDir, %A_ScriptDir%
DetectHiddenWindows, On
CoordMode, ToolTip, window
global isTop:=0, config_obj:="", config_json:="", xlsx_path:="", json_path:="", exportmode:=0, progressbar:=0
, default_config:="
(
{
""xlsx_path"" : """ A_ScriptDir """,
""json_path"" : """ A_ScriptDir """,
""exportmode"" : 0
}
)"
Gui, 主界面:new, -Resize +Hwndid, Excel To Json
Gui, 主界面:Default
Gui, Color, F0F0F0
Menu, 程序_菜单项, Add, 保持在最上方, 保持在最上方
Menu, 程序_菜单项, Add, 打开错误日志, 打开错误日志
Menu, 程序_菜单项, Add, 清空错误日志, 清空错误日志
Menu, 程序_菜单项, Add, 退出程序, 退出程序
Menu, 设置_菜单项, Add, 恢复默认设置, 恢复默认设置
Menu, 关于_菜单项, Add, 关于此程序, 关于
Menu, 菜单栏, Add, 程序, :程序_菜单项
Menu, 菜单栏, Add, 设置, :设置_菜单项
Menu, 菜单栏, Add, 关于, :关于_菜单项
Gui, Menu, 菜单栏
Gui, Add, text, Section xm ym+5, xlsx文件所在路径:
Gui, Add, text, x+2 yp-3 w200 h18 Border +0x8000 vxlsx_path,
Gui, Add, Button, x+0 yp-3 w25 g浏览xlsx, ...
Gui, Add, Button, x+10 g打开xlsx目录, 打开
Gui, Add, text, xs yp+40, json文件存放路径:
Gui, Add, text, x+2 yp-3 w200 h18 Border +0x8000 vjson_path,
Gui, Add, Button, x+0 yp-3 w25 g浏览json, ...
Gui, Add, Button, x+10 g打开json目录, 打开
Gui, Add, text, xs yp+40, exportmode:
Gui, Add, DDL, x+2 yp-3 w30 vexportmode Choose%exportmode% g设置导出模式, 0|1|2|3
Gui, Add, text, x+5 yp+3 w270 r2 vexportmode注释,
Gui, Add, Progress, xs yp+40 w260 h20 -smooth vprogressbar, 0
Gui, Add, Button, xs+275 yp-2 w100 g开始导出, 开始导出
Gui, Add, StatusBar,,
SB_SetParts(270)
gosub, 读取配置
Gui, Show, w400 h170, Excel To Json
SetTimer, statusBar_update, 1000
return
保持在最上方:
if(isTop==0)
{
isTop:=1
Gui, +AlwaysOnTop
}
else
{
isTop:=0
Gui, -AlwaysOnTop
}
Menu, 程序_菜单项, ToggleCheck, 保持在最上方
return
打开错误日志:
if(FileExist(A_ScriptDir . "\errorlog.log"))
Run, %A_ScriptDir%\errorlog.log
else
MsgBox,,, 文件不存在, 5
return
清空错误日志:
FileDelete, %A_ScriptDir%\errorlog.log
FileAppend,, %A_ScriptDir%\errorlog.log
return
恢复默认设置:
FileDelete, %A_ScriptDir%\config.json
gosub, 读取配置
return
关于:
Gui, 关于:new, -SysMenu, 关于此程序
Gui, 关于:Add, text,, 本程序是为ExcelToJson库编写的可视化UI
Gui, 关于:Add, link,, 项目的GitHub地址是:<a href="https://github.com/liuchengsis/ExcelToJson">https://github.com/liuchengsis/ExcelToJson</a>
Gui, 关于:Add, text,, 若有反馈意见可以发issue,或者联系作者QQ441066542
Gui, 关于:Add, Button, Default w30 h20 g关闭关于窗口, OK
Gui, 关于: +owner主界面
Gui, 关于:Show
return
关闭关于窗口:
Gui, 关于:Destroy
return
读取配置:
if(FileExist(A_ScriptDir . "\config.json"))
FileRead, config_json, %A_ScriptDir%\config.json
else
config_json:=default_config, create_jsonfile(A_ScriptDir,"config",ahk_tojson(json_toobj(default_config)))
config_obj:=json_toobj(config_json), xlsx_path:=config_obj.xlsx_path, json_path:=config_obj.json_path, exportmode:=config_obj.exportmode
GuiControl,, xlsx_path, %xlsx_path%
GuiControl,, json_path, %json_path%
GuiControl, ChooseString, exportmode, %exportmode%
gosub,更新注释
return
浏览xlsx:
Gui +OwnDialogs
FileSelectFolder, xlsx_path, *%xlsx_path%, 4, 选择文件夹
config_obj.xlsx_path:=xlsx_path, create_jsonfile(A_ScriptDir,"config",ahk_tojson(config_obj))
GuiControl,, xlsx_path, %xlsx_path%
return
打开xlsx目录:
if(FileExist(xlsx_path))
Run, explorer %xlsx_path%
else
MsgBox,,, 路径不存在, 5
return
浏览json:
Gui +OwnDialogs
FileSelectFolder, json_path, *%json_path%, 4, 选择文件夹
config_obj.json_path:=json_path, create_jsonfile(A_ScriptDir,"config",ahk_tojson(config_obj))
GuiControl,, json_path, %json_path%
return
打开json目录:
if(FileExist(json_path))
Run, explorer %json_path%
else
MsgBox,,, 路径不存在, 5
return
设置导出模式:
GuiControlGet, exportmode
config_obj.exportmode:=exportmode+0, create_jsonfile(A_ScriptDir,"config",ahk_tojson(config_obj))
gosub, 更新注释
return
更新注释:
Switch exportmode
{
Case 0:
exportmode注释:="只导出合并数据后的主表"
Case 1:
exportmode注释:="导出合并数据后的主表和含主键的从表(合并数据后的从表数据中不存在外键)"
Case 2:
exportmode注释:="导出合并数据后的主表和所有原始从表(从表的外键也会保留)"
Case 3:
exportmode注释:="不合并数据,强制导出所有原始表"
}
GuiControl,, exportmode注释, %exportmode注释%
return
开始导出:
GuiControl,, progressbar, 0
excel_tojson(xlsx_path,json_path,exportmode)
return
;GUI动作相关
GuiEscape:
ToolTip
return
退出程序:
GuiClose:
ExitApp
; 更新进度条
progress_update(pos_progress)
{
GuiControl,, progressbar, %pos_progress%
return
}
; 更新状态栏
statusBar_update:
FormatTime, times, A_Now, yyyy-MM-dd HH:mm:ss
Gui, 主界面:Default
SB_SetText(times,2)
return
; 从xlsx_path目录检索xlsx文件并导出json至json_path目录,exportmode决定导出模式
excel_tojson(xlsx_path,json_path,exportmode:=0)
{
static type_True:= Object("json_value", "true", "value", 1)
, type_False:= Object("json_value", "false","value", 0)
, type_Null := Object("json_value", "null", "value","")
dest:=json_path, xlsxlist:=[], starttime:=A_TickCount
loop, Files, %xlsx_path%\*.xlsx, R
{
if A_LoopFileAttrib contains H,S
continue
xlsxlist.Push(A_LoopFileDir . "\" . A_LoopFileName)
}
xl := ComObjCreate("Excel.Application"), xl.DisplayAlerts:=false, win_id:=xl.hWnd
WinGet, p_pid, PID, ahk_id %win_id%
key_main_list:="0", sheetname:="", parent_name:="", master_table:={}, follower_table_haskey:={}, follower_table_nokey:={}, pre_progress:=0, late_progress:=0
for k, v in xlsxlist
{
wb := xl.workbooks.open(v)
loop % wb.worksheets.Count
{
ws:= wb.worksheets[A_Index], ws.Activate
if SubStr(ws.Name,1,1)="!"
continue
SB_SetText("正在解析" . wb.Name . "/" . ws.Name)
, ahk_obj:={}, table_type:=1, table_struct:={}, row:=1, col:=1, index_title:=0, owner_col:=0,text:="", while_ok:=1, blank:=0 ;table_struct[第几列]=>[字段名,类型码]
, InStr(ws.Name,"@") ? (table_type++, parent_name:=SubStr(ws.Name, InStr(ws.Name,"@")+1), sheetname:=SubStr(ws.Name, 1, InStr(ws.Name,"@")-1)) : sheetname:=ws.Name
while while_ok
{
text:=ws.cells[row,col].value
if(!index_title) ;先找标头行
{
text ? blank:=0 : ++blank
if(blank>=10)
Break
pos_sharp:=InStr(text, "#"), (pos_sharp && SubStr(text, pos_sharp+1)="id") ? index_title:=row : row++
continue
}
if(row=index_title && text) ;读标头,确定表的结构
{
if(SubStr(text,1,1)!="!")
pos_sharp:=InStr(text, "#"), table_struct.Push([SubStr(text, 1, pos_sharp-1),SubStr(text, pos_sharp+1)]), ((table_type>=2 && RegExMatch(SubStr(text, pos_sharp+1),"i)^owner$")) && owner_col:=col)
col++
continue
}
else if(row=index_title && !text)
{
row++, col:=1
continue
}
if(row>index_title) ;读内容
{
table_type>=2 ? ctrl_value:=ws.cells[row,owner_col].text : ctrl_value:=ws.cells[row,1].text
if(ctrl_value="")
{
while_ok:=0
Break
}
key_main:=ws.cells[row,1].text
if(key_main!="")
{
if key_main not in %key_main_list% ; 主键重名检测
key_main_list.=","key_main, ahk_obj[key_main]:={}, (table_type==2 && table_type++)
else
{
row++
continue
}
}
else
row_obj:={}
while col<=table_struct.Count()
{
text:=ws.cells[row,col].value, (text="null" && text:=type_Null.Clone())
Switch table_struct[col][2]
{
Case "{}", "[]":
text:=json_toobj(text).Clone()
, key_main!="" ? ahk_obj[key_main][(table_struct[col][1])]:=text : row_obj[(table_struct[col][1])]:=text
Case "bool", "boolean":
text:=ws.cells[row,col].text
if(RegExMatch(text,"i)^true$"))
text:=type_True.Clone()
else if(RegExMatch(text,"i)^false$"))
text:=type_False.Clone()
else
errlog("Type_Error_Boolean",wb.Name,ws.Name,row,col)
key_main!="" ? ahk_obj[key_main][(table_struct[col][1])]:=text : row_obj[(table_struct[col][1])]:=text
Case "owner":
key_main!="" ? ahk_obj[key_main]["owner"]:=text : row_obj["owner"]:=text
Case "id":
(key_main!="" && ahk_obj[key_main][(table_struct[col][2])]:=text)
Case "timestamp":
txet:=Unix_timestamp(text), key_main!="" ? ahk_obj[key_main][(table_struct[col][1])]:=text : row_obj[(table_struct[col][1])]:=text
Case "timestamp13":
txet:=Unix_timestamp(text,13), key_main!="" ? ahk_obj[key_main][(table_struct[col][1])]:=text : row_obj[(table_struct[col][1])]:=text
Default:
key_main!="" ? ahk_obj[key_main][(table_struct[col][1])]:=text : row_obj[(table_struct[col][1])]:=text
}
col++
}
(key_main="" && ahk_obj.Push(row_obj.Clone()))
if(!while_ok)
Break
}
row++, col:=1
}
Switch table_type ;将ahk对象缓存
{
Case 1:
if(!master_table.HasKey(sheetname))
master_table[sheetname]:=ahk_obj.Clone()
Case 2:
if(!follower_table_nokey.HasKey(sheetname))
follower_table_nokey[sheetname]:=[ahk_obj.Clone(),parent_name,0]
Case 3:
if(!follower_table_haskey.HasKey(sheetname))
follower_table_haskey[sheetname]:=[ahk_obj.Clone(),parent_name,0]
}
ws:=""
}
wb.Close(), wb:="", pre_progress++, progress_update(Ceil(50*pre_progress/xlsxlist.Count()))
}
; 先备份缓存,以便依据不同模式导出
master_table_cache:={}, follower_table_nokey_cache:={}, follower_table_haskey_cache:={}, count:=0
for k, v in master_table
master_table_cache[k]:=ahk_tojson(v), SB_SetText("缓存" . k . ".json")
for k, v in follower_table_nokey
follower_table_nokey_cache[k]:=ahk_tojson(v[1]), SB_SetText("缓存" . k . ".json")
for k, v in follower_table_haskey
follower_table_haskey_cache[k]:=ahk_tojson(v[1]), SB_SetText("缓存" . k . ".json")
; 从缓存中取出对象,依据引用关系重组对象后导出json
for k, v in follower_table_nokey ;k->sheetname, v->[ahk_obj.Clone(),parent_name,0]
{
if(v[3]==0)
{
SB_SetText("合并:表" . k . "--->" . v[2])
if(follower_table_haskey.HasKey(v[2])) ;先在带主键的从表集合中查找是否存在被引用的主表
{
for i, j in v[1] ;i->数组下标 j->row_obj
{
parent_key:=j.owner, j.Delete("owner")
if(!follower_table_haskey[v[2]][1][parent_key].HasKey(k))
follower_table_haskey[v[2]][1][parent_key][k]:=j
else if(follower_table_haskey[v[2]][1][parent_key].HasKey(k) && typeof(follower_table_haskey[v[2]][1][parent_key][k])=="object")
obj_cache:=follower_table_haskey[v[2]][1][parent_key][k].Clone(), follower_table_haskey[v[2]][1][parent_key][k]:=[], follower_table_haskey[v[2]][1][parent_key][k].Push(obj_cache,j)
else if(follower_table_haskey[v[2]][1][parent_key].HasKey(k) && typeof(follower_table_haskey[v[2]][1][parent_key][k])=="array")
follower_table_haskey[v[2]][1][parent_key][k].Push(j)
}
v[3]:=1
}
else if(master_table.HasKey(v[2])) ;再查找主表集合
{
for i, j in v[1]
{
parent_key:=j.owner, j.Delete("owner")
if(!master_table[v[2]][parent_key].HasKey(k))
master_table[v[2]][parent_key][k]:=j
else if(master_table[v[2]][parent_key].HasKey(k) && typeof(master_table[v[2]][parent_key][k])=="object")
obj_cache:=master_table[v[2]][parent_key][k].Clone(), master_table[v[2]][parent_key][k]:=[], master_table[v[2]][parent_key][k].Push(obj_cache,j)
else if(master_table[v[2]][parent_key].HasKey(k) && typeof(master_table[v[2]][parent_key][k])=="array")
master_table[v[2]][parent_key][k].Push(j)
}
v[3]:=1
}
else
v[3]:=-1, SB_SetText("表" . k . "合并失败,找不到父表"), errlog("Table_Error_NoMaster",k,v[2])
}
}
for k, v in follower_table_haskey ;k->sheetname, v->[ahk_obj.Clone(),parent_name,0]
{
SB_SetText("合并:表" . k . "--->" . v[2])
if(v[3]==0 && follower_table_haskey.HasKey(v[2])) ;带主键的从表先在同类中查找父表
{
if(follower_table_haskey[v[2]][2]!=k)
{
for i, j in v[1] ;i->follower_key j->ahk_obj[follower_key]
{
parent_key:=j.owner, j.Delete("owner")
if(!follower_table_haskey[v[2]][1][parent_key].HasKey(k))
follower_table_haskey[v[2]][1][parent_key][k]:=(j.id!="" ? {j.id:j} : j)
else if(follower_table_haskey[v[2]][1][parent_key].HasKey(k) && typeof(follower_table_haskey[v[2]][1][parent_key][k])=="object")
obj_cache:=follower_table_haskey[v[2]][1][parent_key][k].Clone(), follower_table_haskey[v[2]][1][parent_key][k]:=[], follower_table_haskey[v[2]][1][parent_key][k].Push(obj_cache,(j.id!="" ? {j.id:j} : j))
else if(follower_table_haskey[v[2]][1][parent_key].HasKey(k) && typeof(follower_table_haskey[v[2]][1][parent_key][k])=="array")
follower_table_haskey[v[2]][1][parent_key][k].Push((j.id!="" ? {j.id:j} : j))
}
v[3]:=1
}
else
v[3]:=-1, SB_SetText("表" . k . "合并失败,循环引用"), errlog("Table_Error_Circular_Reference",k,v[2])
}
else if(v[3]==0 && master_table.HasKey(v[2])) ;再查找主表集合
{
for i, j in v[1]
{
parent_key:=j.owner, j.Delete("owner")
if(!master_table[v[2]][parent_key].HasKey(k))
master_table[v[2]][parent_key][k]:=(j.id!="" ? {j.id:j} : j)
else if(master_table[v[2]][parent_key].HasKey(k) && typeof(master_table[v[2]][parent_key][k])=="object")
obj_cache:=master_table[v[2]][parent_key][k].Clone(), master_table[v[2]][parent_key][k]:=[], master_table[v[2]][parent_key][k].Push(obj_cache,(j.id!="" ? {j.id:j} : j))
else if(master_table[v[2]][parent_key].HasKey(k) && typeof(master_table[v[2]][parent_key][k])=="array")
master_table[v[2]][parent_key][k].Push((j.id!="" ? {j.id:j} : j))
}
v[3]:=1
}
else
v[3]:=-1, SB_SetText("表" . k . "合并失败,找不到父表"), errlog("Table_Error_NoMaster",k,v[2])
}
if(exportmode==0) ;只导出合并数据后的主表
{
total:=master_table.Count()
for k, v in master_table
SB_SetText("导出" . k . ".json"), count++, s:=ahk_tojson(v), create_jsonfile(dest,k,s), late_progress++, progress_update(Ceil(50+50*late_progress/total))
}
else if(exportmode==1) ;导出合并数据后的1类和3类表
{
total:=master_table.Count() + follower_table_haskey.Count()
for k, v in master_table
SB_SetText("导出" . k . ".json"), count++, s:=ahk_tojson(v), create_jsonfile(dest,k,s), late_progress++, progress_update(Ceil(50+50*late_progress/total))
for k, v in follower_table_haskey
(v[3]==1 && (SB_SetText("导出" . k . ".json"), count++, s:=ahk_tojson(v[1]), create_jsonfile(dest,k,s), late_progress++, progress_update(Ceil(50+50*late_progress/total))))
}
else if(exportmode==2) ;导出合并数据后的1类表和所有原始2类3类表
{
total:=master_table.Count() + follower_table_haskey_cache.Count() + follower_table_nokey_cache.Count()
for k, v in master_table
SB_SetText("导出" . k . ".json"), count++, s:=ahk_tojson(v), create_jsonfile(dest,k,s), late_progress++, progress_update(Ceil(50+50*late_progress/total))
for k, v in follower_table_haskey_cache
SB_SetText("导出" . k . ".json"), count++, create_jsonfile(dest,k,v), late_progress++, progress_update(Ceil(50+50*late_progress/total))
for k, v in follower_table_nokey_cache
SB_SetText("导出" . k . ".json"), count++, create_jsonfile(dest,k,v), late_progress++, progress_update(Ceil(50+50*late_progress/total))
}
else if(exportmode==3) ;不导出合并数据后的表,强制导出所有原始表
{
total:=master_table_cache.Count() + follower_table_haskey_cache.Count() + follower_table_nokey_cache.Count()
for k, v in master_table_cache
SB_SetText("导出" . k . ".json"), count++, create_jsonfile(dest,k,v), late_progress++, progress_update(Ceil(50+50*late_progress/total))
for k, v in follower_table_haskey_cache
SB_SetText("导出" . k . ".json"), count++, create_jsonfile(dest,k,v), late_progress++, progress_update(Ceil(50+50*late_progress/total))
for k, v in follower_table_nokey_cache
SB_SetText("导出" . k . ".json"), count++, create_jsonfile(dest,k,v), late_progress++, progress_update(Ceil(50+50*late_progress/total))
}
else if(exportmode==-1) ;不导出,调试用
s:=""
xl.Quit()
ElapsedTime:=A_TickCount-starttime
Process, Close, %p_pid%
SB_SetText("导出完成,共导出 " . count . " 个json文件,耗时 " . ElapsedTime . " ms")
return
}
; JSon字符串转AHK对象
json_toobj(s)
{
static q:=Chr(34)
, type_True := Object("json_value", "true", "value", 1)
, type_False:= Object("json_value", "false","value", 0)
, type_Null := Object("json_value", "null", "value","")
static rep:=[ ["\\","\u005c"], ["\" q,q], ["\/","/"], ["\r","`r"], ["\n","`n"], ["\t","`t"], ["\b","`b"], ["\f","`f"] ]
if !(p:=RegExMatch(s, "O)[{\[]", r))
return
stack:=[], result:=[], arr:=result, isArr:=(r[0]="["), key:=(isArr ? 1 : ""), keyok:=0
While p:=RegExMatch(s, "O)\S", r, p+StrLen(r[0]))
{
Switch r[0]
{
Case "{", "[":
r1:=[], (isArr && !keyok ? (arr.Push(r1), keyok:=1) : arr[key]:=r1)
, stack.Push(arr, isArr, key, keyok), arr:=r1, isArr:=(r[0]="["), key:=(isArr ? 1 : ""), keyok:=0
Case "}", "]":
if stack.Length()<4
Break
keyok:=stack.Pop(), key:=stack.Pop(), isArr:=stack.Pop(), arr:=stack.Pop()
Case ",":
key:=(isArr ? key+1 : ""), keyok:=0
Case ":":
(!isArr && keyok:=1)
Case q:
i:=p, re:="O)" q "[^" q "]*" q
While (p:=RegExMatch(s, re, r, p+StrLen(r[0])-1)) && SubStr(StrReplace(r[0],"\\"),-1,1)="\"
{} ; 用循环避免正则递归太深
if !p ;if p=0,代表已经递归到s结尾处,如果每一个匹配对象都是"**\"这样反斜杠结尾的话很有可能得到p=0
Break
r1:=SubStr(s, i+1, p+StrLen(r[0])-i-2) ;返回当初那个匹配对象剥离了引号和结尾\的干净值
if InStr(r1, "\") ;如果还有\,那么就代表还有要转义的字符
{
For k, v in rep
r1:=StrReplace(r1, v[1], v[2])
v:="", k:=1
While i:=RegExMatch(r1, "i)\\u[0-9a-f]{4}",, k)
v.=SubStr(r1,k,i-k) . Chr("0x" SubStr(r1,i+2,4)), k:=i+6 ;将 Unicode 字符转换为字符串
r1:=v . SubStr(r1,k) ;r1现在是替换了所有 Unicode 字符后的字符串
}
(isArr or keyok) ? (isArr && !keyok ? (arr.Push(r1), keyok:=1) : arr[key]:=r1) : key:=r1
Default:
if(RegExMatch(s, "O)[^\s\{\}\[\],:]+", r, p)!=p)
Break
Switch r[0]
{
Case "true":
r1:=type_True.Clone()
Case "false":
r1:=type_False.Clone()
Case "null":
r1:=type_Null.Clone()
; Case "undefined":
; r1:=type_Null.Clone() ;默认不将undefined转换为null
Default:
r2:=r[0]
if r2 is number
r1:=r[0]+0
else
r1:=r[0]
}
(isArr or keyok) ? ((isArr && !keyok) ? (arr.Push(r1), keyok:=1) : arr[key]:=r1) : key:=r1
}
}
return result
}
; AHK对象转JSon字符串
ahk_tojson(obj, space:="")
{
static q:=Chr(34)
, type_True := Object("json_value", "true", "value", 1)
, type_False:= Object("json_value", "false","value", 0)
, type_Null := Object("json_value", "null", "value","")
static rep:=[ ["\\","\"], ["\" q,q]
; , ["\/","/"], ["\u003c","<"], ["\u003e",">"], ["\u0026","&"] ; 默认不替换 "/-->\/" 与 html特殊字符 "<、>、&-->\uXXXX"
, ["\r","`r"], ["\n","`n"], ["\t","`t"], ["\b","`b"], ["\f","`f"] ] ;前面是json的转义字符,后面是AHK的
if !IsObject(obj)
{
if obj is Number
return ([obj].GetCapacity(1) ? q . obj . q : Round(obj)-obj=0 ? Round(obj) : Round(obj,2))
For k, v in rep
obj:=StrReplace(obj, v[2], v[1])
; While RegExMatch(obj, "O)[^\x20-\x7e]", r) ; 默认不替换 "Unicode字符-->\uXXXX"
; obj:=StrReplace(obj, r[0], Format("\u{:04x}",Ord(r[0])))
return q . obj . q
}
isArr:=1
For k, v in obj ;这里的作用就是判断obj是简单数组还是关联数组
if (k!=A_Index) and !(isArr:=0)
Break
if (!isArr and obj.Count()=2) and obj.HasKey("json_value") and ((k:=obj["json_value"])="true" or k="false" or k="null")
return k
s:="", NewSpace:=space . " ", f:=A_ThisFunc
For k, v in obj
if !(k="" or IsObject(k)) ;这里是一个递归,如果取到了键,则继续递归,取不到则递归结束
s.= "`r`n" NewSpace . (isArr ? "" : %f%(k . "") ": ") . %f%(v,NewSpace) . ","
s:=Trim(s,",") . "`r`n" space
return isArr ? "[" s "]" : "{" s "}"
}
; 类型判断,五种ahk基本类型
typeof(v)
{
if IsObject(v)
return ObjGetCapacity(v)>ObjCount(v) ? "object" : "array"
return v="" || [v].GetCapacity(1) ? "string" : InStr(v,".") ? "float" : "integer"
}
; 创建json文件
create_jsonfile(path,filename,s)
{
file := FileOpen(path . "\" . filename . ".json", "w", "UTF-8"), file.Write(s), file.Close()
return
}
; 错误日志打印
errlog(errcode,param1:="",param2:="",param3:="",param4:="")
{
FormatTime, t, A_Now, yyyy-MM-dd HH:mm:ss
Switch errcode
{
Case "Type_Error_Boolean":
newlog:= t . "=>" . errcode . ":布尔类型错误`n位于" . param1 . "表" . param2 . "行" . param3 . "列" . param4 . "`n"
Case "Table_Error_NoMaster":
newlog:= t . "=>" . errcode . ":表引用错误`n表" . param1 . "找不到父表" . param2 . "`n"
Case "Table_Error_Circular_Reference":
newlog:= t . "=>" . errcode . ":表引用错误`n表" . param1 . "与表" . param2 . "存在循环引用`n"
}
FileAppend, %newlog%, %A_ScriptDir%\errorlog.log
return
}
; 将格式日期转换为时间戳
Unix_timestamp(formattedtime,len:=10)
{
s:="", d:=[31,28,31,30,31,30,31,31,30,31,30,31], v:=[1970,1,1,0,0,0], 时差:=Round((A_Now-A_NowUTC)/10000)
if formattedtime is not time
{
RegExMatch(formattedtime,"\S.+\S", str)
if str is not time
{
arr:= StrSplit(str,["-","/",":",":","年","月","日",A_Space])
for i, j in arr
v[i]:=j
if(v[1]<1601 || v[1]>9999 || v[2]<1 || v[2]>12 || v[3]<1 || v[3]>d[v[2]] || v[4]<0 || v[4]>23 || v[5]<0 || v[5]>59 || v[6]<0 || v[6]>59)
return "Unix_Timestamp_Error"
for i, j in v
s.=Format("{:" . (i=1 ? "04" : "02") . "}", j)
}
else
s:=str
}
else
s:=formattedtime
EnvSub, s, 19700101000000, Seconds
return len=13 ? (s-时差*3600)*1000 : s-时差*3600
}