3

I have a string like { "a": "1", "b": "2", "c": "3", "asefw": "Chintan" } and I need to properly indent it to print it out in html.

Right now, I'm using a combination of google-code-prettify (for syntax highlighting), and ruby's JSON object to print it out, but the indentation is slightly off: enter image description here

Here's the relevant code from my Rails view:

.container
  .row.demo-samples
    .span9{:style => "\n-moz-border-radius: 8px 8px 6px 6px;\nborder-radius: 8px 8px 6px 6px;"}
      -@content.each do |content|
        %pre
          %code.prettyprint
            =JSON.pretty_generate(JSON[content.content])

It looks like everything but the first row is indented too much. Any idea how to fix this?

4

2 回答 2

3

此常见问题解答条目可能会有所帮助....

http://haml.info/docs/yardoc/file.FAQ.html#q-preserve

于 2013-07-09T23:11:10.613 回答
0

我遇到了同样的问题,我写了这段小代码:

var pretty_json = function (ele, level, key) {
    var cls = [];
    if (key) {
        cls.push('pretty-json-key');
        ele = ele + ':';
    } else if (typeof ele === 'number') {
        cls.push('pretty-json-number');
    } else if (typeof ele === 'boolean' && ele) {
        cls.push('pretty-json-true');
    } else if (typeof ele === 'boolean' && !ele) {
        cls.push('pretty-json-false');
    } else if (typeof ele === 'string') {
        cls.push('pretty-json-string');
    } else {
        cls.push('pretty-json-null');
        ele = '<i class="fa fa-ban"></i>';
    }

    var output = '<span ';
    if (key) output += 'style="margin-left:' + (INDENT * level) + 'px" ';
    output += ('class="' + cls.join(' ') + '">' + ele + '</span>');
    console.log(output);
    return output;
};

var eachRecursive = function (obj, level, s) {
    for (var k in obj) {
        if (!obj.hasOwnProperty(k)) continue;
        if (typeof obj[k] == "object" && obj[k] !== null) {
            s.push(pretty_json(k, level, true));
            s.push("<br>");
            eachRecursive(obj[k], level + 1, s);
        } else {
            s.push(pretty_json(k, level, true));
            s.push(pretty_json(obj[k], level));
            s.push("<br>");
        }
    }
};

var make_pretty_json = function (json_str) {
    var json_obj = JSON.parse(json_str);
    var output = [];
    eachRecursive(json_obj, 1, output);
    return output.join('');
};

http://jsfiddle.net/qwwqwwq/kefn7/37/

基本策略是递归地遍历对象并将每个键和值替换为 html 标记和适当的类(即键、数字、字符串、布尔值、空值都有自己的类)。使用内联样式属性根据对象树的深度设置缩进。

于 2014-05-04T00:32:04.173 回答