Explorar o código

ZF-5280 - add JSON pretty-printer

git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19202 44c647ce-9c0f-0410-b52a-842ac1e357ba
stas %!s(int64=16) %!d(string=hai) anos
pai
achega
38b9bb3a42
Modificáronse 1 ficheiros con 43 adicións e 0 borrados
  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 if (is_array($simpleXmlElementObject))
     } // End of function _processXml.
     } // 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;
+   }
 }
 }