LoginSignup
0
3

More than 5 years have passed since last update.

python2とpython3でjson.dumpsのインデントの挙動が違う

Last updated at Posted at 2017-08-20

python2.7とpython3.6でindentオプションを指定した時のjson.dumpsの挙動が違う。python2だと改行コードの前にスペースが一つはいっているが、python3だとはいっていない。

実験

コード

import json
json.dumps({"name": 'aaa', "age": 21}, sort_keys=True, indent=2)

結果

python2.7.8

'{\n  "age": 21, \n  "name": "aaa"\n}'

python3.6.0

> '{\n  "age": 21,\n  "name": "aaa"\n}'

原因と対応

原因

Issue 16333: Trailing whitespace in json dump when using indent - Python tracker

対策

separators=(',',': ')をjson.dumpsのオプションに追加する。

import json
json.dumps({"name": 'aaa', "age": 21}, sort_keys=True, indent=2, separators=(',', ': '))
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3