Home > Software engineering >  Truncate long strings inside json in python
Truncate long strings inside json in python

Time:05-11

Given some json

[
    {
        "default_value": "True",
        "feature_name": "feature_1",
        "active_on": "remote_1,remote_2,remote_3,remote_4,remote_5,remote_6,remote_7"
    },
    {
        "feature_name": "special_super_duper_feature_wooooooooot",
        "active_on": "remote_2"
    }
]

how do I truncate values longer than, say, 20 chars:

[
    {
        "default_value": "True",
        "feature_name": "feature_1",
        "active_on": "remote_1,remote_2..."
    },
    {
        "feature_name": "special_super_dup...",
        "active_on": "remote_2"
    }
]

as generically as possible?

EDIT: Here's a more generic example to fit:

[
    {
        "a": {"b": "c"},
        "d": "e"
    },
    {
        "a": [{"b": "dugin-walrus-blowing-up-the-view-and-ruining-page-frame"}]
    }
]

The endgame here is to make "pretty-print" for arbitrary json. I'm wondering whether there's a nice way to do that using only standard library.

CodePudding user response:

You can work with a string limiter this way:

[:17]   '...'

And work from loop in your values to readjust its values.

Example:

a = 'test text to work with limiter length'
a = a[:17]   '...'
print(a)

Result:

test text to work...

CodePudding user response:

I'm not aware of any built-in method to do this, but one approach might be to just iterated over the list, then over the items in each dictionary, and apply a string slice to each item, like so:

def truncate(d: dict):
    for k, v in d.items():
        d.update({k: str(v)[:17]   "..."})
    return d

json_trunc = list(map(lambda x: truncate(x), json_orig))

It would definitely be possible to include the truncating function in the list comprehension too if desired, I've just separated them here for readability / understandability.

  • Related