Python中将(字典,列表等)变量格式化成字符串输出

比如原始的List变量的值是这种:

1 [{"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"]}]

 

而想要将其输出为带缩进的,树状的,很漂亮的效果,那么可以通过这样的方法:

1 import json
2  
3 #demoDictList is the value we want format to output
4 jsonDumpsIndentStr = json.dumps(demoDictList, indent=1)
5 print "jsonDumpsIndentStr=",jsonDumpsIndentStr

 

输出:

 1 [
 2  {
 3   "yearMonth": {
 4    "month": {
 5     "string": "November",
 6     "value": "11"
 7    },
 8    "year": {
 9     "string": "2012",
10     "value": "2012"
11    }
12   },
13   "reservedMonthList": [
14    "2",
15    "3",
16    "8",
17    "9",
18    "10",
19    "11",
20    "12",
21    "13",
22    "17",
23    "18",
24    "19",
25    "20",
26    "21",
27    "22",
28    "23"
29   ]
30  },
31  {
32   "yearMonth": {
33    "month": {
34     "string": "December",
35     "value": "12"
36    },
37    "year": {
38     "string": "2012",
39     "value": "2012"
40    }
41   },
42   "reservedMonthList": [
43    "7",
44    "8",
45    "9",
46    "10",
47    "11",
48    "12",
49    "13",
50    "14",
51    "15",
52    "16",
53    "21",
54    "22",
55    "23",
56    "24",
57    "25",
58    "26",
59    "27",
60    "28",
61    "30",
62    "31"
63   ]
64  }
65 ]


传递给json.dumps时,没有添加indent=1的话:

1 import json
2  
3 #demoDictList is the value we want format to output
4 jsonDumpsIndentStr = json.dumps(demoDictList)
5 print "jsonDumpsIndentStr=",jsonDumpsIndentStr

 

则就是输出的,前面已经给出的,紧凑型的,没有缩进和换行的,原始的JSON字符串了:

1 [{"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"]}]

 

posted on 2013-08-09 01:00  JasonKwok  阅读(1229)  评论(0)    收藏  举报

导航