漂亮的打印JSON与python中的填充

时间:2016-06-02 17:34:24

标签: 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 =文件名,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()

有更优雅的方法吗?

1 个答案:

答案 0 :(得分:0)

此版本打印到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()保留所有格式,并使用ljust()填充左栏。

[编辑后查找数据格式化后的最大宽度]