python 进阶(9) -- JSON 排版


你忘了我们的破风格言是什么,风在前,无惧


方法

使用 json 的 indent 参数可以控制缩进来达到排版 json

>>> data
{'programmers': [{'firstName': 'Brett', 'lastName': 'McLaughlin', 'email': 'aaaa'}, {'firstName': 'Jason', 'lastName': 'Hunter', 'email': 'bbbb'}, {'firstName': 'Elliotte', 'lastName': 'Harold', 'email': 'cccc'}], 'authors': [{'firstName': 'Isaac', 'lastName': 'Asimov', 'genre': 'science fiction'}, {'firstName': 'Tad', 'lastName': 'Williams', 'genre': 'fantasy'}, {'firstName': 'Frank', 'lastName': 'Peretti', 'genre': 'christian fiction'}], 'musicians': [{'firstName': 'Eric', 'lastName': 'Clapton', 'instrument': 'guitar'}, {'firstName': 'Sergei', 'lastName': 'Rachmaninoff', 'instrument': 'piano'}]}

>>> print(json.dumps(data))
{"programmers": [{"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa"}, {"firstName": "Jason", "lastName": "Hunter", "email": "bbbb"}, {"firstName": "Elliotte", "lastName": "Harold", "email": "cccc"}], "authors": [{"firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction"}, {"firstName": "Tad", "lastName": "Williams", "genre": "fantasy"}, {"firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction"}], "musicians": [{"firstName": "Eric", "lastName": "Clapton", "instrument": "guitar"}, {"firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano"}]}

>>> print(json.dumps(data, indent=2))
{
  "programmers": [
    {
      "firstName": "Brett",
      "lastName": "McLaughlin",
      "email": "aaaa"
    },
    {
      "firstName": "Jason",
      "lastName": "Hunter",
      "email": "bbbb"
    },
    {
      "firstName": "Elliotte",
      "lastName": "Harold",
      "email": "cccc"
    }
  ],
  "authors": [
    {
      "firstName": "Isaac",
      "lastName": "Asimov",
      "genre": "science fiction"
    },
    {
      "firstName": "Tad",
      "lastName": "Williams",
      "genre": "fantasy"
    },
    {
      "firstName": "Frank",
      "lastName": "Peretti",
      "genre": "christian fiction"
    }
  ],
  "musicians": [
    {
      "firstName": "Eric",
      "lastName": "Clapton",
      "instrument": "guitar"
    },
    {
      "firstName": "Sergei",
      "lastName": "Rachmaninoff",
      "instrument": "piano"
    }
  ]
}