这是我用来完成所需功能的一些临时代码,想分享一下:
v = {'has': {1: [213124,1243215,143541,531322], 'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}
print(pretty(v))
输出:
{
'has': {
1: [
213124,
1243215,
143541,
531322
],
'plants{}': 'yes',
'animals': 'yes',
'cryptonite': 'no'
},
'name': 'Earth'
}
不好看的代码:
def pretty(obj, starters='{[', enders='}]', items=','):
_all = starters+enders+items
tabs, i, s, inside_quotes = 0, 0, str(obj), ['"', False]
def step_char(c):
nonlocal tabs, i, inside_quotes
tabs += (c in starters) - (c in enders)
_c = (not (s[max(i-1, 0)] in _all and c == ' ')) * (('\n'+(tabs*'\t')*(c in set(_all)))*(c in set(enders))*(not inside_quotes[1]) + c + ('\n'+tabs*'\t')*(c in set(_all))*(not sum([s[i:].startswith(e+ii) for e in enders for ii in items]))*(not inside_quotes[1]))
inside_quotes = in_quotes(i, s, inside_quotes)
i += 1
return _c
return ''.join(list(map(step_char, s)))
def in_quotes(index, string, last):
in_string = last
for quote in ['"""', "'''", '"', "'"]:
if string[index].startswith(quote):
if in_string[1] and in_string[0] == quote:
in_string[1] = False
break
elif not in_string[1]:
in_string = [quote, True]
break
return in_string
None
对象怎么样?它将被转换为null
。您需要手动将这些null
对象转换为None
。 - Ryan Chou