-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonFormat.php
More file actions
86 lines (84 loc) · 2.38 KB
/
Copy pathjsonFormat.php
File metadata and controls
86 lines (84 loc) · 2.38 KB
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
<?php
if(array_search('-f', $argv)){
$path = $argv[$argc-1];
$instr = file_get_contents($path);
}else{
$instr = $argv[$argc-1];
}
$res = json_decode($instr);
if($res){
//trim space
$instr = str_replace("\n", "", $instr);
//unicode to utf
//$instr=preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $instr);
function uni2utf($matches){
return iconv('UCS-2BE', 'UTF-8', pack('H4', $matches[1]));
}
$instr=preg_replace_callback("#\\\u([0-9a-f]{4})#i", "uni2utf", $instr);
$len = strlen($instr);
$flag = 0;
$str = '';
for($i=0; $i<$len; $i++){
$char = $instr{$i};
switch($char){
case '"':
$flag++;
$str .= $char;
break;
case " ":
if($flag%2!=0){
$str .= $char;
}
break;
default:
$str .= $char;
break;
}
}
//correct json str, format print
$prem = 0;
$flag = 0;
$len = strlen($str);
for($i=0; $i<$len; $i++){
$char = $str{$i};
$nxtChar = $i<($len-1) ? $str{$i+1} : '';
if($char == '"'){
$flag++;
}
if($flag%2==0){
if($char == "{" || $char == "["){
echo $char."\n";
$prem += 2;
printf("%{$prem}s", "");
}else if($char == "}" || $char == "]"){
if($nxtChar == ","){
//$prem = $prem-1>0 ? $prem-1 : 0;
echo $char;
}else if($nxtChar == "}" || $nxtChar == "]"){
echo $char."\n";
$prem = $prem-2>0 ? $prem-2 : 0;
printf("%{$prem}s", "");
}else{
$prem = $prem-2>0 ? $prem-2 : 0;
printf("%{$prem}s", "");
echo $char;
}
}else if($char == ","){
echo $char."\n";
printf("%{$prem}s", "");
}else{
echo $char;
if($nxtChar == "}" || $nxtChar == "]"){
$prem = $prem-2>0 ? $prem-2 : 0;
echo "\n";
printf("%{$prem}s", "");
}
}
}else{
echo $char;
}
}
echo "\n";
}else{
//wrong json str, point error location
}