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


   

       Python中将(字典,列表等)变量格式化成(漂亮的,树形的,带缩进的,JSON方式的)字符串输出:

变量类型是列表,列表中每个值是个字典类型变量。

格式化输出的效果,希望是那种树状结构,带缩进的,而不希望是原始的字符串堆积的那种。

后来经过折腾,找到了一个相对比较省事,且效果比较好的办法。

特此整理如下:

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

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"]}]

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

?

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

print "json_list=",json_list;

然后就可以看到打印出来的效果就是我们所期望的,很漂亮的,树状的,带缩进的,JSON方式的,效果了

结果如下:

[
  {
    "yearMonth": {
      "year": {
        "string": "2012",
        "value": "2012"
      },
      "month": {
        "string": "November",
        "value": "11"
      }
    },
    "reservedMonthList": [
      "2",
      "3",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "23"
    ]
  },
  {
    "yearMonth": {
      "year": {
        "string": "2012",
        "value": "2012"
      },
      "month": {
        "string": "December",
        "value": "12"
      }
    },
    "reservedMonthList": [
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "21",
      "22",
      "23",
      "24",
      "25",
      "26",
      "27",
      "28",
      "30",
      "31"
    ]
  }
]

print json.loads(json_list)

[{u'yearMonth': {u'month': {u'string': u'November', u'value': u'11'}, u'year': {u'string': u'2012', u'value': u'2012'}}, u'reservedMonthList': [u'2', u'3', u'8', u'9', u'10', u'11', u'12', u'13', u'17', u'18', u'19', u'20', u'21', u'22', u'23']}, {u'yearMonth': {u'month': {u'string': u'December', u'value': u'12'}, u'year': {u'string': u'2012', u'value': u'2012'}}, u'reservedMonthList': [u'7', u'8', u'9', u'10', u'11', u'12', u'13', u'14', u'15', u'16', u'21', u'22', u'23', u'24', u'25', u'26', u'27', u'28', u'30', u'31']}]


你可能感兴趣的:(python,格式化输出)