1

In the request (I didn't write it) this little script:

<script type="text/javascript">
    function oncallback(e) { 
        $('#message').html(e.data);
    } 
</script>

Writes to the browser window a JSON string:

{"event":"success","method":"sale","request_id":"275936ad-83c0-4afd-88ff-6943c4ee2781","response_code":"A01","response_description":"TEST APPROVAL","trace_number":"8da65a44-3c07-4590-8b62-302f533aaa18","authorization_code":"123456","customer_token":"0InRBKpTSy2VlUL0wbLZlQ","paymethod_token":"vPSGgKycRXWWqkxiiXm_IA","total_amount":"8.88","order_number":"COR-199287","version_number":"1.0","last_4":"1111","method_used":"visa","hash_method":"md5","save_token":"true","expire_month":"02","expire_year":"2020","signature":"731c764db3d3d5c25e371fbffd331e5c","utc_time":"636584905150041669"}

I would like to have the string display in the browser window all nice and pretty like this:

{
    "event": "success",
    "method": "sale",
    "request_id": "275936ad-83c0-4afd-88ff-6943c4ee2781",
    "response_code": "A01",
    "response_description": "TEST APPROVAL",
    "trace_number": "8da65a44-3c07-4590-8b62-302f533aaa18",
    "authorization_code": "123456",
    "customer_token": "0InRBKpTSy2VlUL0wbLZlQ",
    "paymethod_token": "vPSGgKycRXWWqkxiiXm_IA",
    "total_amount": "8.88",
    "order_number": "COR-199287",
    "version_number": "1.0",
    "last_4": "1111",
    "method_used": "visa",
    "hash_method": "md5",
    "save_token": "true",
    "expire_month": "02",
    "expire_year": "2020",
    "signature": "731c764db3d3d5c25e371fbffd331e5c",
    "utc_time": "636584905150041669"
}

I have tried variations of JSON.stringify() but not getting anywhere...

such as:

JSON.stringify($('#message').html(e.data)),undefined, 2);

Is this possible?

Full script here: https://www.calligraphydallas.com/stuff/forteco.new.php

If you want to see the final JSON response string, click the Pay Now button and use:

card number: 4111111111111111
expiry: anything in the future
CVV: any 3-digit number

edit: Still no joy :(

<html>
<?php
    $APILoginID         = 'LI9KrwLnR';
    $SecureTransKey     = '5ULeuwN7N3h4';   
    $ordernumber        = 'COR-199287';
    $totalamount        = 8.88;
    $method             = 'sale';
    $version            = '1.0';
    $millitime          = microtime(true) * 1000;
    $utc                = number_format(($millitime * 10000) + 621355968000000000 , 0, '.', '');
    $data               = "$APILoginID|$method|$version|$totalamount|$utc|$ordernumber||";
    $hash               = hash_hmac('md5',$data,$SecureTransKey);
    $expire             = number_format(($millitime * 10000) + 621355968001000000 , 0, '.', '');
?>
<head>

<style>
    #message {
    white-space: pre;
    }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
    function oncallback(e) { 
        var jsonString = $('#message').html(e.data);
        var str = JSON.stringify(jsonString, null, 2);
        $('#message').html(str);
    }
</script>

<script type="text/javascript" src="https://sandbox.forte.net/checkout/v1/js"></script>    <!-- sandbox -->
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<pre id="message"></pre>
    <button api_login_id=<?php echo $APILoginID;?>
    version_number=<?php echo $version;?>
    method=<?php echo $method;?>
    callback="oncallback"
    total_amount=<?php echo $totalamount;?>
    utc_time=<?php echo $utc;?>
    signature=<?php echo $hash;?>
    billing_email_address_attr="required"
    order_number=<?php echo $ordernumber;?>
    consumer_id="123ABC"
    >Pay Now</button>
</body>
</html>

Edit:

If this is the string:

{"event":"success","method":"sale","request_id":"e26ff0a0-1762-40f7-a747-f1d1e3da298d","response_code":"A01","response_description":"TEST APPROVAL","trace_number":"3f3ace6b-8e6c-4d53-8252-0e4df4af01bf","authorization_code":"123456","customer_token":"pNEFB2w4S5G5uhw4RAOnDA","paymethod_token":"tOxI8ULPQ8yJAk2zkIDFGQ","total_amount":"8.88","order_number":"COR-199287","version_number":"1.0","last_4":"1111","method_used":"visa","hash_method":"md5","save_token":"true","expire_month":"02","expire_year":"2020","signature":"31a7e07128e5a5d792dc0403b610a2fb","utc_time":"636585555449053529"}

produced by this little script:

<script>
    function oncallback(e) { 
        $('#message').html(e.data);
    } 
</script>

<html>
<body>
<pre id="message"></pre>
<button callback="oncallback"></button>
</body>
</html>

It seems like this should work:

<script>
    function oncallback(e) { 
        JSON.stringify($('#message').html(e.data),null,2);
    } 
</script>

<html>
<body>
<pre id="message"></pre>
<button callback="oncallback"></button>
</body>
</html>

But it does not. It produces the same string.

Thoughts anyone?

James
  • 161
  • 1
  • 10
  • What do you mean *Is this possible*? Did you try your stringift approach? What happened? Possible duplicate of [How can I pretty-print JSON using JavaScript?](https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript) – Aaron Brager Apr 05 '18 at 02:59
  • @AaronBrager That question doesn't solve his problem. It's a possible duplicate of https://stackoverflow.com/questions/16862627/json-stringify-output-to-div-in-pretty-print-way . If you try the correct pretty-printing method, putting it into a div does not have the desired result. – Owen Campbell Apr 05 '18 at 03:01

2 Answers2

0

JSON.stringify output to div in pretty print way

Change your <div> to a <pre> and it should work.

var stuff = {
  "event": "success",
  "method": "sale",
  "request_id": "275936ad-83c0-4afd-88ff-6943c4ee2781",
  "response_code": "A01",
  "response_description": "TEST APPROVAL",
  "trace_number": "8da65a44-3c07-4590-8b62-302f533aaa18",
  "authorization_code": "123456",
  "customer_token": "0InRBKpTSy2VlUL0wbLZlQ",
  "paymethod_token": "vPSGgKycRXWWqkxiiXm_IA",
  "total_amount": "8.88",
  "order_number": "COR-199287",
  "version_number": "1.0",
  "last_4": "1111",
  "method_used": "visa",
  "hash_method": "md5",
  "save_token": "true",
  "expire_month": "02",
  "expire_year": "2020",
  "signature": "731c764db3d3d5c25e371fbffd331e5c",
  "utc_time": "636584905150041669"
};

var str = JSON.stringify(stuff, null, 2); // spacing level = 2
$('#message').html(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <pre id='message'>
</pre>
</body>

</html>

To fit your example:

<script>
    function oncallback(e) { 
        var formatted_json = JSON.stringify(e.data, null, 2);
        $('#message').html(formatted_json);
    } 
</script>

<html>
<body>
<pre id="message"></pre>
<button callback="oncallback"></button>
</body>
</html>
Owen Campbell
  • 622
  • 1
  • 5
  • 10
  • Thanks Owen. Changing the div to pre sounded promising, but no joy. Still have a string. You see that I do not have access to "stuff" ahead of time, right? It's a server response to submitting the transaction. I am trying to display the server response as pretty instead of string. – James Apr 05 '18 at 03:46
  • Yes I know you don't have it, but notice that the only time I use it is in my `JSON.stringify()` code which you tried. How come you are unable to put the data through `JSON.stringify` and then append it to a `
    ` tag? See my edit for an example fitting your current code.
    – Owen Campbell Apr 05 '18 at 23:25
  • Hooray!! Thank you so much Owen, that did the trick. I had to JSON.parse it first (saw that in a similar thread) -- and now it works perfect. Never occurred to me to stringify the e.data. Here's the tweak: var formatted_json = JSON.stringify(JSON.parse(e.data), null, 2); Thank you very much! – James Apr 05 '18 at 23:49
  • I'm glad! If it solved your problem please check the checkmark by the answer! – Owen Campbell Apr 07 '18 at 00:21
0

If e.data is a JSON string, you can use pre tag to display, but if it doesn't work, you can use JS-beautify library to do format your JSON string.

json_string = `{"success":true,"message":"","result":[{"MarketName":"BTC-2GIVE","High":0.00000073,"Low":0.00000068,"Volume":790977.87467493,"Last":0.00000072,"BaseVolume":0.56122489,"TimeStamp":"2018-04-05T02:47:06.43","Bid":0.00000071,"Ask":0.00000072,"OpenBuyOrders":98,"OpenSellOrders":913,"PrevDay":0.00000070,"Created":"2016-05-16T06:44:15.287"},{"MarketName":"BTC-ABY","High":0.00000089,"Low":0.00000084,"Volume":4401237.65534640,"Last":0.00000084,"BaseVolume":3.76668598,"TimeStamp":"2018-04-05T02:46:16.137","Bid":0.00000084,"Ask":0.00000086,"OpenBuyOrders":223,"OpenSellOrders":1572,"PrevDay":0.00000087,"Created":"2014-10-31T01:43:25.743"},{"MarketName":"BTC-ADA","High":0.00002334,"Low":0.00002172,"Volume":48936131.81817110,"Last":0.00002193,"BaseVolume":1099.49743017,"TimeStamp":"2018-04-05T02:47:35.6","Bid":0.00002193,"Ask":0.00002194,"OpenBuyOrders":4187,"OpenSellOrders":11490,"PrevDay":0.00002245,"Created":"2017-09-29T07:01:58.873"},{"MarketName":"BTC-ADT","High":0.00000409,"Low":0.00000377,"Volume":8790985.59406923,"Last":0.00000380,"BaseVolume":34.55251768,"TimeStamp":"2018-04-05T02:47:39.163","Bid":0.00000380,"Ask":0.00000384,"OpenBuyOrders":186,"OpenSellOrders":2137,"PrevDay":0.00000395,"Created":"2017-07-03T21:08:06.11"}]}`;
formatted = js_beautify(json_string,{
 indent_char:" ",
 indent_size:2,
 "indent_with_tabs": false,
});
document.getElementById('result').innerText = formatted;
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.7.5/beautify.min.js"></script>
<pre id= 'result'></pre>

Reference: JSON.stringify output to div in pretty print way

Hank Phung
  • 2,059
  • 1
  • 23
  • 38