4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでjson編集

Posted at

pythonによってjsonの編集をする際は
jsonをdict型に変換すると楽。

まずはjsonを読み込んでみる
sample.json
{
    "object": "food",
    "object_list": [
        "rice",
        "meat",
        "salad"
    ]
}
edit_json.py
import json

with open('./sample.json', 'r') as js:
    dict_json = json.load(js) #jsonをdict型に変換

print(type(dict_json))
print(dict_json)

$ python edit_json.py

<class 'dict'>
{'object': 'food', 'object_list': ['rice', 'meat', 'salad']}
続いてjsonを編集して保存してみる
edit_json.py
import json

with open("./sample.json", "r") as js:
    dict_json = json.load(js) #jsonをdict型に変換

dict_json["object"] = "color"

color_list = [
    "red",
    "blue",
    "yellow"
]

dict_json["object_list"] = color_list

#./edited.jsonファイルを作成し、dict_jsonを書き込み。
with open("./edited.json", "w") as js:
    json.dump(dict_json, js, indent = 4) #indentを指定すると綺麗に整形されます

$ python edit_json.py
で以下jsonファイルが生成されます。

edited.json
{
    "object": "color",
    "object_list": [
        "red",
        "blue",
        "yellow"
    ]
}

以上でした🍞

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?