Просмотр исходного кода

ZF-5280 - add JSON pretty-printer

git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19202 44c647ce-9c0f-0410-b52a-842ac1e357ba
stas 16 лет назад
Родитель
Сommit
38b9bb3a42
1 измененных файлов с 43 добавлено и 0 удалено
  1. 43 0
      library/Zend/Json.php

+ 43 - 0
library/Zend/Json.php

@@ -336,4 +336,47 @@ class Zend_Json
 
         } // End of if (is_array($simpleXmlElementObject))
     } // End of function _processXml.
+    
+    /**
+     * Pretty-print JSON string
+     * 
+     * Use 'indent' option to select indentation string - by default it's a tab
+     * 
+     * @param string $json Original JSON string
+     * @param array $options Encoding options
+     * @return string
+     */
+    public static function prettyPrint($json, $options = array())
+    {
+        $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
+        $result = "";
+        $indent = 0;
+        
+        $ind = "\t";
+        if(isset($options['indent'])) {
+            $ind = $options['indent'];
+        }
+        
+        foreach($tokens as $token) {
+            if($token == "") continue;
+            
+            $prefix = str_repeat($ind, $indent);
+            if($token == "{" || $token == "[") {
+                $indent++;
+                if($result[strlen($result)-1] == "\n") {
+                    $result .= $prefix;
+                }
+                $result .= "$token\n";
+            } else if($token == "}" || $token == "]") {
+                $indent--;
+                $prefix = str_repeat($ind, $indent);
+                $result .= "\n$prefix$token";                
+            } else if($token == ",") {
+                $result .= "$token\n";
+            } else {
+                $result .= $prefix.$token;
+            }
+        }
+        return $result;
+   }
 }