How to display a Javascript object in Edge Trace?

Using a Javascript policy in Apigee Edge policy flow, I set a context variable. When I view that variable in Edge Trace, I see "[object Object]". Not helpful.

2026-not-helpful.png

The test code looks like this:

var calculator = {
    "objName": "calculator",
    "random": Math.random(),
    "start": new Date(),
    "calculate": function getPrimes(max) {
        var sieve = [],
            i, j, primes = [];
        for (i = 2; i <= max; ++i) {
            if (!sieve[i]) {
                // i has not been marked -- it is prime
                primes.push(i);
                for (j = i << 1; j <= max; j += i) {
                    sieve[j] = true;
                }
            }
        }
        return primes;
    }
};


context.setVariable("calculator", calculator);

What can I do to see the JS object more clearly?

Solved Solved
1 4 1,696
1 ACCEPTED SOLUTION

Easiest way to do this is to stringify the object to JSON:

context.setVariable("calculator", JSON.stringify(calculator));

View solution in original post

4 REPLIES 4

Easiest way to do this is to stringify the object to JSON:

context.setVariable("calculator", JSON.stringify(calculator));

yep, that's the ticket!

The key is to stringify the object before storing it into the context variable.

JSON.stringify() works for this purpose, for most JS hashes. Your code would look like this:

context.setVariable("calculator", JSON.stringify(calculator));

That won't work properly if you want to see the content of the properties of type function . JSON.stringify(), by definition, omits properties of type function from the output. To rectify this, you'd need to use a replacer function, like this:

function replacer (key, val) {
  return (typeof val === 'function') ? '' + val : val;
}
var s = JSON.stringify(calculator, replacer);
context.setVariable("calculator", s);

And the result is like so:

2025-much-better.png

But even there, you don't get to see the source of the function. On the positive side, you do get to see that it IS a function.

Much better!

Dear @Dino,

You need to convert calculator into string using the below code and you will see the values :

var str_calculator = JSON.stringify(calculator);
context.setVariable("str_calculator", str_calculator);

The output will be seen as shown below:

str_calculator = {"objName":"calculator","random":0.1834675877236256,"start":"2016-02-24T17:56:47.049Z"}

Regards,

Amar