[英]pretty printing JSON with padding in python
我正在嘗試將一組JSON鍵/值寫入一個包含漂亮打印和填充的文件,如下所示:
{
"k1DaySummary" : "1 day summary",
"k1HourSummary" : "1 hour summary",
"k1MonthSummary" : "1 month summary",
"k1WeekSummary" : "1 week summary",
"kAlarmAPIError" : "error - please make sure your API supports this feature",
"kAlarmFrameCount" : "Alarm Frame Count",
"kAlarmMaxFPS" : "Alarm Max FPS",
"kAlarms" : "Alarms",
"kAnalyze" : "Analyze",
"kApiUrl" : "api url",
"kApplyingChanges" : "Applying changes. Please wait",
"kArrangingImages" : "arranging images",
"kAt" : "at",
"kAuthSuccess" : "authentication success",
"kAuthenticating" : "authenticating",
"kAwake1" : "Keep display on",
"kAwake2" : "(when viewing footage)",
"kBannerAPICheckFailed" : "API check failed",
"kBannerCannotDeleteNeedOne" : "Cannot delete, need at least one"
}
我目前正在以下列方式使用json.dumps
(f = filename,k =鍵組)
#beautifies a given file
def beautify(f,k):
print "Beautifying ",f
pFh=open ('pretty-'+f,"w")
pFh.write(json.dumps(k,indent=4,sort_keys=True, ensure_ascii=False))
pFh.close()
這不會填充值列。 我能想到的唯一解決方案是不使用json_dumps
而是使用python字符串格式化,計算最長密鑰(mK)的長度,然后迭代遍歷數組,使用`
這是另一種方法:
#beautifies a given file
def beautify(fi,ki):
print "Beautifying ",fi
w = len (max(ki, key=len))
pretty=[]
for k,v in ki.iteritems():
line = " \"%s\"%s:\"%s\"" %(k,' '*(w-len(k)+1),v)
pretty.append(line)
pFh=open ('pretty-'+fi,"w")
pFh.write("{\n")
pFh.write(',\n'.join(pretty))
pFh.write("\n}\n")
pFh.close()
是否有更優雅的方式來做到這一點?
此版本打印到stdout,您可以將其重定向到新文件:
import json
w = 0
pairs = [] # holds the formatted data
for k,v in ki.iteritems():
k = json.dumps(k)
v = json.dumps(v) + ","
pairs.append((k, v))
w = max(w, len(k)) # find the widest key value, after formatting
print '{'
for k,v in pairs:
print ' ', k.ljust(w), ':', v
print '}'
它通過使用json.dumps()
保留任何格式,並使用json.dumps()
ljust()
。
[編輯后查找數據格式化后的最大寬度]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.