0
0

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 5 years have passed since last update.

【メモ】Jsonファイルでネストした要素を削除する方法

Last updated at Posted at 2019-06-27

実行環境

Windows 10
Visual Studio Code
Python3.7

ネスト構造になっているjsonファイルから特定の要素を消したいぜ

Python3を使ってネスト構造になったjsonファイルから要素削除したいぜ!ってことでやってみました。

[
    {
        "age": 19,
        "height": 181.4,
        "sex": "male"
    },
    {
        "age": 29,
        "height": 161.0,
        "sex": "female"
    },
]

上記のようなinput.jsoファイルがあったと仮定します。
ここで、年齢(age)が29歳の人の要素は要らねぇ!ってなったとします。
その時、以下のコードで削除でき、かつ、削除した新しいoutput.jsonファイルを作成できます。

# coding: utf-8
import json

f = open('input.json', 'r', encoding="utf-8")
jsonData = json.load(f)

for i in range(len(jsonData)):
    if json.dumps(jsonData[i]['age'], sort_keys = True, indent = 4, ensure_ascii=False) == "29":
        jsonData[i].clear()
    
    print(json.dumps(jsonData[i], sort_keys = True, indent = 4, ensure_ascii=False))

f.close()

f = open('output.json', 'w', encoding="utf-8")
json.dump(jsonData, f, indent='\t', ensure_ascii=False)

ちなみに、これの実行結果はこうなります。

[
    {
        "age": 19,
        "height": 181.4,
        "sex": "male"
    },
    {},
]

見て貰ったらわかりますが、{}が消えてないんですよね。
そこのやり方わからなかったので、もしわかる人いたら教えてください。

ポイント

print(json.dumps(jsonData[i], sort_keys = True, indent = 4, ensure_ascii=False))

print文の一番最後にある「ensure_ascii=False」は日本語の文字化けを解消するためのコードです。
日本語がjsonファイルに入らないなら不要...なはずです。
日本語がある場合は絶対に要ります!

私はjsonファイルの書き込む所でこれを書き忘れていた為に、ず~っと文字化けが治らず苦労しました。

0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?