读取JSON文件并更改i中的内容

2024-05-16 14:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个movie_data.json文件。我想读取json文件并将99popularity更改为popularity

[
  {
    "99popularity": 83.0,
    "director": "Victor Fleming",
    "genre": [
      "Adventure",
      " Family",
      " Fantasy",
      " Musical"
    ],
    "imdb_score": 8.3,
    "name": "The Wizard of Oz"
  },
  {
    "99popularity": 88.0,
    "director": "George Lucas",
    "genre": [
      "Action",
      " Adventure",
      " Fantasy",
      " Sci-Fi"
    ],
    "imdb_score": 8.8,
    "name": "Star Wars"
  },
]

我试图读取json文件

import json

with open('movie_data.json') as f:
    data = json.load(f)

print(data['director'])

它给了我一个错误-

Traceback (most recent call last):
  File "json-read.py", line 6, in <module>
    print(data['director'])
TypeError: list indices must be integers or slices, not str

Tags: 文件namejsondatamoviefantasyimdbscore
1条回答
网友
1楼 · 发布于 2024-05-16 14:44:24

加载到文件中,然后可以使用pop属性交换密钥:

import json

with open('movie_data.json') as fh:
    file = json.load(fh)

for entry in file:
    try:
        # remove the key with pop and re-set it with the value that pop returns
        entry['popularity'] = entry.pop('99popularity')
    except KeyError as e: # Key isn't found, skip
        continue

with open('new_movie_data.json', 'w') as fh:
    fh.write(json.dumps(file, indent=3)) # indent will format your file

相关问题 更多 >