Value formatting in keyvaluemap components

Hi - I’ve written a transformer using JSON.stringify to nicely format a JSON object. But when it’s passed to a Key Value Map component that formatting gets thrown away.

Would be really nice if that formatting was preserved, so complicated objects could be readable. Thanks!

Little code sample to show what I mean:

var benefits = {{get_user.data.benefits}};

Object.keys(benefits).forEach(function(key, index) {
benefits[key] = JSON.stringify(benefits[key], null, 2);
});
return benefits

Hey @markbenepass, and welcome to the community! Just to make sure I understand correctly - you’re using a JS transformer to apply this function to your query’s data? If so, you should be able to reference that transformed data in the key value map component (https://docs.retool.com/docs/transformers). Is it the JSON.stringify formatting you want to preserve, or the null replacing? Or both?

Hi Justin, thanks for the reply. Here’s the use-case, will try and explain it well:

I have a query that I display in a table, and one column contains Key/Value Maps that I frequently need to explore. On the backend it’s python dicts that turn into JSONFields in the DB. I have a transformer that I’m using to pull out the column that from the query, and do some mild modifications to the data. The data structure is actually a nested dictionary, something like:
{“primary_key”: {
“key1” : “value1”,
“key2”: “value2”,
},}

I want to use the Key Value Map Component in Retool to nicely display that data (column -> transformer), but because of the nested dicts the “value” part of the Key Value Map is still really hard to read. When I use JSON.stringify in the transfomer it does a nice job of formatting (indents, replacer function), but that formatting isn’t passed along to the Key Value Component. So the value portion is just one big string dump, instead of maintaining indents for readability. Does that make sense?

Thanks for the help!

Hey @markbenepass, sorry for the delay here, the team has been enjoying a few days off :slight_smile:

Yes, your use case totally makes sense. Two approaches that might help here:

  1. Create a transformer as query

There are two ways to create transformers in Retool: attached to a specific query (e.g. in that query’s window) or as a separate query in of itself (click on the “transformers” tab in the query editor). If you choose the latter method, you can reference query in the transformer (e.g. {{ query.data }}) the transformer’s returned data directly via {{ transformer.data }} - that may preserve the formatting.

  1. Do the prettifying in the key value reference

You can skip the transformer step and just use your Object.keys loop in the “Data” field for your key value component. Forgive me if I mess up syntax, but it should look something like this:

{{
    Object.keys(get_user.data.benefits).forEach(key => 
        JSON.stringify(key, null, 2);
    )
}}

Let me know if either of these work!