![](http://python-guide.work/wp-content/themes/cocoon-master/images/b-woman.png)
Pythonで
・jsonデータの書き換え
ができます!
![](http://python-guide.work/wp-content/themes/cocoon-master/images/b-woman.png)
この記事では
・変数に設定したjsonデータの書き換え
をします!
※for文内で繰り返し書き換えます。
![](http://python-guide.work/wp-content/themes/cocoon-master/images/b-woman.png)
書き換えは
・「jsonデータ(dict型)」を作成
・「jsonデータ(dict型)」を書き換え
・「jsonデータ(dict型)」を「jsonデータ(str型)」へ変換
により実現します!
コード
ここでは例として
・jsonデータの「key1」の「値」の書き換え
をします。
※for文内で繰り返し書き換えます。
import json
# jsonデータ(dict型)を作成
json_dict = {
"key1": "xx"
}
for i in range(1, 5):
# jsonデータ(dict型)を書き換え
json_dict["key1"] = i
# jsonデータ(dict型)をjsonデータ(str型)へ変換
json_str = json.dumps(json_dict)
# 書き換えられたことを確認
print(json_str)
実行結果
jsonデータを書き換えができました。
※for文内で繰り返し書き換えできました。
![実行結果](https://python-guide.work/wp-content/uploads/2023/12/py_json_rewrite_001.png)
参考
上記のコードで使用した以下の詳細は、公式サイトをご確認ください。
●標準ライブラリ「json」モジュールの「dumps」