open-policy-agent/opa

Indented/"pretty-printed" JSON marshaling

Closed this issue · 3 comments

What is the underlying problem you're trying to solve?

We're using SpaceLift for automating Terraform management. SpaceLift uses OPA for notification policies, which determines when (and what) to comment on PRs to SpaceLift-connected repos.

Presenting contextual plan output (i.e. new resource state) is easiest by serializing the state object to JSON. (This is what one of the examples in the Spacelift docs suggests.) However, both interpolating the object via sprintf or using json.marshal both produce compressed, single-line JSON. This is hard for human readers to interpret.

Describe the ideal solution

Add an optional Boolean parameter to json.marshal() (defaulting to false) that indicates the resultant JSON string should be indented.

pretty = json.marshal(objectFoo, true)
normal = json.marshal(objectFoo)
alsoNormal = json.marshal(objectFoo, false) 

Describe a "Good Enough" solution

Add a new built-in (e.g. json.marshal_indent() that functions identically to json.marshal, but with indented/multi-line output.

Additional Context

Updating the existing builtin would be backwards-incompatible. A new json.marshal_indent() seems like a good option. Feel free to contribute if you'd like.

@ashutosh-narkar Does Rego/OPA support polymorphic functions/optional parameters? Part of the rationale behind adding a new optional parameter was so any existing [one-parameter] calls to json.marshal() wouldn't be affected.

Does Rego/OPA support polymorphic functions/optional parameters?

Currently not. Only print is a variadic builtin function.