Display JSON pretty in a textarea control

In an application I am using heavily JSON default as the data-format. To make debugging a bit more easy I am working on a toolbar to be able to check the content of the JSON objects.

Normally I use JSONLint most of the time to prettify (and validate) the JSON so it becomes a bit easier to read and check. But this copy and paste habit becomes more and more obnoxious so there I wanted to have a toolbar (like the debug toolbar) to have a good overview of the JSON objects.

However if you write the JSON object to a computed field or text area field (inputTextarea control in the XPages world) it is just plain, unformatted text. Not pretty for the eye and not much helpful for the brain.

So I tested a simple approach which turns out to run just fine. I display the json object in a textarea input control and then with CSJS I format the content. Here is some sample code:

<xp:inputTextarea id=”input-fieldx” defaultValue=”#{javascript:App.currCollection}”>
</xp:inputTextarea>
<xp:button value=”Make Pretty” id=”button1″>
<xp:eventHandler event=”onclick” submit=”false”>
<xp:this.script>
<![CDATA[var name = x$(‘#{id:input-fieldx}’).attr(“name”);
prettyPrint(name);]]>
</xp:this.script>
</xp:eventHandler>
</xp:button>
<xp:scriptBlock id=”scriptBlock1″>
<xp:this.value>
<![CDATA[function prettyPrint(id) {
var obj = dojo.byId(id);
var ugly = obj.value;
var json = dojo.fromJson(ugly);
var pretty = JSON.stringify(json, undefined, 4);
obj.innerHTML = pretty;
dojo.setAttr(id,”rows”,10);
}]]>
</xp:this.value>
</xp:scriptBlock>

Here is what it looks like:

json-before

The content how it looks initially.

json-after

The content how it looks like after running the code.

Note I had to include the [ ] signs in my code to make the JSON valid due to circumstances in my code, I removed it from the sample code above.

At least now I understand my JSON objects again and I can avoid some copy and paste to JSONLint 🙂

This is probably my last blog of this year so I would like to wish you some wonderful Christmas days. Take care and best wishes for a healthy 2017!

 

 

Advertisements

2 thoughts on “Display JSON pretty in a textarea control

  1. Keith Strickland 2016-December-25 / 5:57 pm

    If the JSON is retrieved via an Ajax/XHR request then why not use Chrome Dev Tools?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s