---
title: "用js模拟PHP的print_r功能"
author: "muyu"
date: "2009-11-10T11:51:24Z"
tags: []
slug: "js-php-print-r"
draft: false
lastmod: "2009-11-10T12:02:37Z"
id: 513486
url: "https://muyu.iteye.com/blog/513486"
---

最近参与一个PHP与flash交互的项目，数据格式采用json。一些返回信息中包含中文，中文字符值大于 255 的以 %uxxxx 格式存储，不利于调试代码。同事提供了一个网址，可以把json数据通过Ajax在服务器端解析，并返回经过语法着色的关联数组，非常清晰。

 

我抱着学习的目的，用js模拟了该功能。主要是递归处理对象：

 

```
 $(document).ready(function(){
    $('#btn').click(function(){
      var jsonStr = $('#jsonData').val();
      var json = eval('('+jsonStr+')');
      (function(){
        var print_r = function(o, depth) {
          var result = '';
          depth || (depth=1);
          var indent = new Array(4*depth+1).join(' ');
          var indentNext = new Array(4*(depth+1)+1).join(' ');
          var indentNextTwo = new Array(4*(depth+2)+1).join(' ');
          var tmp = '';
          var type = typeof o;
          switch(type) {
            case 'string':
            case 'number':
            case 'boolean':
            case 'undefined':
            case 'function':
              tmp += indent + indentNext + o + "\n";
              break;
            case 'object':
            default:
              for(var key in o) {
                tmp += indentNextTwo + '[' + key + '] = ';
                tmp += print_r(o[key], (depth+1));
              }
          }
          result += type + "\n";
          result += indentNext + '(' + "\n";
          result += tmp;
          result += indentNext + ')' + "\n";
          return result;
        };
        alert(print_r(json));
      }(json));
    });
  });
```

 注：上述代码需要jquery框架

 

\-------------

演示

\-------------

输入：{"error":\["\\u627e\\u4e0d\\u5230\\u8be5\\u6848\\u4ef6\\u4fe1\\u606f"]}

弹出：

 

![打印出类似print_r的关联数组](http://dl.iteye.com/upload/picture/pic/49027/aaf60cee-c35c-38ff-bcb3-c2ec2015ff7f.jpg)

 

完整的html demo文件，请下载。