給定一些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"
}
]
我如何截斷超過 20 個字符的值:
[
{
"default_value": "True",
"feature_name": "feature_1",
"active_on": "remote_1,remote_2..."
},
{
"feature_name": "special_super_dup...",
"active_on": "remote_2"
}
]
盡可能通用?
編輯:這是一個更通用的示例:
[
{
"a": {"b": "c"},
"d": "e"
},
{
"a": [{"b": "dugin-walrus-blowing-up-the-view-and-ruining-page-frame"}]
}
]
這里的結局是為任意 json 制作“漂亮的列印”。我想知道是否有一種僅使用標準庫的好方法。
uj5u.com熱心網友回復:
您可以通過這種方式使用字串限制器:
[:17] '...'
并在您的值中回圈作業以重新調整其值。
例子:
a = 'test text to work with limiter length'
a = a[:17] '...'
print(a)
結果:
test text to work...
uj5u.com熱心網友回復:
我不知道有任何內置方法可以做到這一點,但一種方法可能是遍歷串列,然后遍歷每個字典中的專案,并將字串切片應用于每個專案,如下所示:
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))
如果需要,肯定也可以在串列理解中包含截斷函式,我只是為了可讀性/可理解性將它們分開。
uj5u.com熱心網友回復:
這是我的看法:
import collections
...
def truncate_strings(obj: collections.abc.Iterable, truncate: int, suffix: str = "...") -> int:
"""
@param obj: generic iterable - object to truncate. Implemented for dicts and lists.
Extensible by adding new types to isinstance.
@param truncate: int - total str length to be set. value 0 to disable.
@param suffix: str [Optional] - the truncation string suffix
@returns count: int - number of strings truncated
"""
if not truncate or not obj or isinstance(obj, str):
return 0
count = 0
if isinstance(obj, dict):
for key_ in obj.keys():
if not key_:
return 0
if isinstance(obj.get(key_), str):
if len(obj[key_]) > truncate - len(suffix):
count = 1
obj[key_] = obj[key_][:truncate - len(suffix)] suffix
else:
count = truncate_strings(key_, truncate, suffix)
elif isinstance(obj, collections.abc.Iterable):
for item in obj:
count = truncate_strings(item, truncate, suffix)
return count
請注意,此函式在可迭代物件上是遞回的,因此很長的串列會殺死您的呼叫堆疊。不過應該在合理大小的 json 上作業(在 1k 個專案 json 陣列上測驗)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475785.html
