相当打印JSON转储 [英] Pretty print JSON dumps
本文介绍了相当打印JSON转储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用这段代码将一些 dict
打印成JSON:
import json
d = {'a':'blah','b':'foo','c':[1,2,3]}
print json.dumps(d,indent = 2,分隔符=(',',':'))
输出: / strong>
{
/ pre>
a:blah,
c:[
1,
2,
3
],
b:foo
}
这是一个太多(每个列表元素的换行符)。
我应该使用哪种语法...
{
a:blah,
c:[1,2,3],
b:foo
}
而不是
解决方案>编写自己的JSON序列化程序:
import numpy
INDENT = 3
SPACE =
NEWLINE =\\\
def to_json(o, level = 0):
ret =
如果isinstance(o,dict):
ret + ={+ NEWLINE
comma =
k,v in o.iteritems():
ret + =逗号
逗号=,\
ret + = SPACE * INDENT *(level + 1)
ret + =''+ str(k)+':'+ SPACE
ret + = to_json(v,level + 1)
ret + = NEWLINE + SPACE * INDENT *级别+}
elif isinstance(o,basestring):
ret + ='''+ o +''
elif isinstance(o,list):
ret + =[+,。join([to_json(e,level + 1)for e in o])+]
elif isinstance(o,bool):
ret + trueif o elsefalse
elif isinstance(o,int):
ret + = str(o)
elif isinstance(o,float):
ret + ='%.7g'%o
elif isinstance(o,numpy.ndarray)和numpy.issubdtype(o.dtype,numpy.integer):
ret + =[+','。 join(map(str,o.flatten())。 tolist()))+]
elif isinstance(o,numpy.ndarray)和numpy.issubdtype(o.dtype,numpy.inexact):
ret + =[+',' .join(map(lambda x:'%.7g'%x,o.flatten()。tolist()))+]
else:
raise TypeError(Unknown type'%s 'json serialization'%str(type(o)))
return ret
inputJson = {'a':'blah','b':'foo','c' :[1,2,3]}
print to_json(inputJson)
输出: / p>
{
a:blah,
c:[1,2,3 ],
b:foo
}
I use this code to pretty print some
dict
into JSON :import json d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]} print json.dumps(d, indent = 2, separators=(',', ': '))
Output :
{ "a": "blah", "c": [ 1, 2, 3 ], "b": "foo" }
This is a little bit too much (newline for each list element!).
Which syntax should I use to have ...
{ "a": "blah", "c": [1, 2, 3], "b": "foo" }
instead ?
解决方案Write your own JSON serializer:
import numpy INDENT = 3 SPACE = " " NEWLINE = "\n" def to_json(o, level=0): ret = "" if isinstance(o, dict): ret += "{" + NEWLINE comma = "" for k,v in o.iteritems(): ret += comma comma = ",\n" ret += SPACE * INDENT * (level+1) ret += '"' + str(k) + '":' + SPACE ret += to_json(v, level + 1) ret += NEWLINE + SPACE * INDENT * level + "}" elif isinstance(o, basestring): ret += '"' + o + '"' elif isinstance(o, list): ret += "[" + ",".join([to_json(e, level+1) for e in o]) + "]" elif isinstance(o, bool): ret += "true" if o else "false" elif isinstance(o, int): ret += str(o) elif isinstance(o, float): ret += '%.7g' % o elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.integer): ret += "[" + ','.join(map(str, o.flatten().tolist())) + "]" elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.inexact): ret += "[" + ','.join(map(lambda x: '%.7g' % x, o.flatten().tolist())) + "]" else: raise TypeError("Unknown type '%s' for json serialization" % str(type(o))) return ret inputJson = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]} print to_json(inputJson)
Output:
{ "a": "blah", "c": [1,2,3], "b": "foo" }
这篇关于相当打印JSON转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文