Reputation: 2132
I have a movie_data.json
file. I want to read the json
file and change 99popularity
to 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"
},
]
I tried to read the json file
import json
with open('movie_data.json') as f:
data = json.load(f)
print(data['director'])
It was giving me error -
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
Upvotes: 0
Views: 90
Reputation: 13126
Load in the file, and then you can use the pop
attribute to swap the key:
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
Upvotes: 3