chintanparikh
chintanparikh

Reputation: 1682

Pretty printing a JSON string in HTML

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;"}
      [email protected] 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?

Upvotes: 3

Views: 3220

Answers (2)

qwwqwwq
qwwqwwq

Reputation: 7329

I encountered the same problem and I wrote this little piece of code:

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/

Basic strategy is to traverse the object recursively and replace each key and value with an html tag, with appropriate class (i.e. keys, numbers, strings, booleans, nulls all have their own class). Indentation is set depending on the depth into the object tree using an inline style attribute.

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19889

This FAQ entry might help....

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

Upvotes: 3

Related Questions