1

I need to beautify an existing view through a userscript (TamperMonkey). The code works in JSFiddle (see http://jsfiddle.net/2phrogm5/), but not where I need it: inside the Zabbix web interface.

To replicate the issue:

JSON.stringify({"asd": {"asd": 3}}, null, 4)

Expected result:

"{
    "asd": {
        "asd": 3
    }
}"

My output:

"{"asd":{"asd":3}}"

The issue doesn't exist using Developer Tools on https://stackoverflow.com/.

I already tried the solution provided in JSON.stringify() array bizarreness with Prototype.js, with no success.

Iron Bishop
  • 1,749
  • 1
  • 7
  • 16
  • it's the same thing booth of your results, just differently written in 1 line and 4 lines – PEPEGA Jun 13 '19 at 13:44
  • @Patte that's not the same: notice the additional spaces, and how stringify is supposed to add formatting when called with 3 parameters. – Iron Bishop Jun 13 '19 at 13:47
  • 1
    Welcome Iron, it looks like someone is overwriting JSON.stringify, why don't you load a polyfill at the end to have it back or implement your own. – gengns Jun 13 '19 at 18:46
  • @gengns your hint was righ: `frontends/php/jsLoader.php: 'var _json_stringify = JSON.stringify;'.'JSON.stringify = function(value) {'.` is the culprit! So the solution is to use `_json_stringify`. Now.. should I answer my own question, or close it? – Iron Bishop Jun 14 '19 at 06:43
  • I'm glad that pointed you to the right direction ^^ Of course, it will be helpful if you answer you own question, others can have similar issues. – gengns Jun 14 '19 at 14:26

1 Answers1

0

Looking at the source code of the Zabbix web interface, you can see where the method is overwritten:

zabbix-software$ egrep -iR "JSON.stringify *="
frontends/php/jsLoader.php:             'var _json_stringify = JSON.stringify;'.
frontends/php/jsLoader.php:             'JSON.stringify = function(value) {'.

The original function is still available, just with a different name: _json_stringify(). The updated jsfiddle is http://jsfiddle.net/u7r8q19g/

update

in Zabbix 5 they put the thing back where it came from or so help me, so now I'm doing:

            if (typeof _json_stringify === "function") {
                item.html(_json_stringify(JSON.parse(text), undefined, 4))
            } else {
                item.html(JSON.stringify(JSON.parse(text), undefined, 4))
            }

thx to How to tell if a JavaScript function is defined

Iron Bishop
  • 1,749
  • 1
  • 7
  • 16