之前折腾Python期间,遇到过,想要把一个变量,格式化输出。
其中:
变量类型是列表,列表中每个值是个字典类型变量。
格式化输出的效果,希望是那种树状结构,带缩进的,而不希望是原始的字符串堆积的那种。
后来经过折腾,找到了一个相对比较省事,且效果比较好的办法。
特此整理如下:
比如原始的List变量的值是这种:
[{"yearMonth": {"month": {"string": "November", "value": "11"}, "year": {"string": "2012", "value": "2012"}}, "reservedMonthList": ["2", "3", "8", "9", "10", "11", "12", "13", "17", "18", "19", "20", "21", "22", "23"]}, {"yearMonth": {"month": {"string": "December", "value": "12"}, "year": {"string": "2012", "value": "2012"}}, "reservedMonthList": ["7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "21", "22", "23", "24", "25", "26", "27", "28", "30", "31"]}]
而想要将其输出为带缩进的,树状的,很漂亮的效果,那么可以通过这样的方法:
import json; #demoDictList is the value we want format to output jsonDumpsIndentStr = json.dumps(demoDictList, indent=1); print "jsonDumpsIndentStr=",jsonDumpsIndentStr;
然后就可以看到打印出来的效果就是我们所期望的,很漂亮的,树状的,带缩进的,JSON方式的,效果了:
[ { "yearMonth": { "month": { "string": "November", "value": "11" }, "year": { "string": "2012", "value": "2012" } }, "reservedMonthList": [ "2", "3", "8", "9", "10", "11", "12", "13", "17", "18", "19", "20", "21", "22", "23" ] }, { "yearMonth": { "month": { "string": "December", "value": "12" }, "year": { "string": "2012", "value": "2012" } }, "reservedMonthList": [ "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "21", "22", "23", "24", "25", "26", "27", "28", "30", "31" ] } ]
对应的,如果上述代码中,传递给json.dumps时,没有添加indent=1的话:
import json; #demoDictList is the value we want format to output jsonDumpsIndentStr = json.dumps(demoDictList); print "jsonDumpsIndentStr=",jsonDumpsIndentStr;
则就是输出的,前面已经给出的,紧凑型的,没有缩进和换行的,原始的JSON字符串了:
[{"yearMonth": {"month": {"string": "November", "value": "11"}, "year": {"string": "2012", "value": "2012"}}, "reservedMonthList": ["2", "3", "8", "9", "10", "11", "12", "13", "17", "18", "19", "20", "21", "22", "23"]}, {"yearMonth": {"month": {"string": "December", "value": "12"}, "year": {"string": "2012", "value": "2012"}}, "reservedMonthList": ["7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "21", "22", "23", "24", "25", "26", "27", "28", "30", "31"]}]
另外,关于json.dumps的更多用法,感兴趣的,也可以去参考官网的解释:
json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)¶ Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object).
If skipkeys is True (default: False), then dict keys that are not of a basic type (str, unicode, int, long, float, bool, None) will be skipped instead of raising a TypeError.
If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result is a str instance consisting of ASCII characters only. If ensure_ascii is False, some chunks written to fp may be unicode instances. This usually happens because the input contains unicode strings or the encoding parameter is used. Unless fp.write() explicitly understands unicode (as in codecs.getwriter()) this is likely to cause an error.
If check_circular is False (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).
If allow_nan is False (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. None (the default) selects the most compact representation.
If separators is an (item_separator, dict_separator) tuple, then it will be used instead of the default (', ', ': ') separators. (',', ':') is the most compact JSON representation.
encoding is the character encoding for str instances, default is UTF-8.
default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
If sort_keys is True (default: False), then the output of dictionaries will be sorted by key.
To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
- json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
Serialize obj to a JSON formatted str. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.
The arguments have the same meaning as in dump().
Note
Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is convered into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
去试试其他各个参数的效果的。
【总结】
python中,想要把变量,格式化输出树状的JSON字符串的效果,可以直接使用
json.dumps(strToFormat, indent=1);
即可实现所需的效果,无需再去使用其他第三方模块了,很是方便。
转载请注明:在路上 » 【整理】Python中将(字典,列表等)变量格式化成(漂亮的,树形的,带缩进的,JSON方式的)字符串输出