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

时间:2019-03-13 14:25:10

标签: python json python-3.x

我有一个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

1 个答案:

答案 0 :(得分:3)

加载文件,然后可以使用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