Search code examples
javascriptxmltextareasapui5pretty-print

Use result of vkbeautify pretty print in TextArea


Hi I have the following TextArea to display a JSON string:

<TextArea id="payloadlabel" width="1000px" height='auto' rows='80' />.

My problem is that the JSON string is not well formatted, see example.

I'm using the library vkbeautify as follows:

var myObj = { 
    "urn.getxxxx": {
         "urn.xxxx" : "cxxxxx-44e9-xxxx-a91b-0000xxxx\\xxxxx\\3xx\\xx\\x\\",
         "urn.xxxx" : "xxxxx",
         "urn.xxxxx" : "x",
         "urn.xxxx": "20xx-07-08xxx:03:41+02:00"
    }
};

var request = JSON.stringify(myObj);
vkbeautify.json(request);
var tryModel = new sap.ui.model.json.JSONModel();
tryModel.setData(request);


var payloadtxta =  sap.ui.getCore().byId(view.createId('payloadlabel'));
payloadtxta.setModel(tryModel);
payloadtxta.setValue(request);

Unfortunately it's not working. The JSON content remains exactly like in the example. What is wrong here?

I have the vkbeautify.js file in my web content and I included it in the index.

<script type="text/javascript" src="vkbeautify.js"></script> 

As I get no error for the vkbeautify method I think I included it in the right way. Suggestions are welcomed if you know any other method to format JSON content any other library or idea. Thank you.


Solution

  • You are using the wrong variable (BTW: JSON.stringify is superfluous as you already have a JSON string):

    var beautifiedObj = vkbeautify.json(myObj);
    
    var payloadtxta = this.byId(view.createId("payloadlabel"));
    payloadtxta.setValue(beautifiedObj);
    

    The model is never used in your example, thus you can remove it or use it as intendend by UI5 and bind the control directly to the model property.

    <TextArea id="payloadlabel" value={/request}" width="1000px" height='auto' rows='80' />.
    
    this.setModel(new sap.ui.model.json.JSONModel({ 
       "request" : vkbeautify.json(myObj)
    });