I have a .json file but I got the tokenId numbering wrong. I need to increase all values of "tokenId" by 1 number
[
{
"Background": "Red",
"Body": "Tunn",
"Hat": "Bambu",
"Outfit": "Pirate",
"Expression": "Sad",
"Accessory": "Rifle",
"tokenId": 0
},
{
"Background": "Lilac",
"Body": "Tunn",
"Hat": "Bicorn",
"Outfit": "Pirate",
"Expression": "Angry",
"Accessory": "Balloons",
"tokenId": 1
},
...
{
"Background": "Green",
"Body": "Tunn",
"Hat": "Bicorn",
"Outfit": "Pirate",
"Expression": "Sad",
"Accessory": "Balloons",
"tokenId": 3000
},
is it possible to do this with python? i created this .json file with python.
I tried this code, but I get an error
import json
with open('traits.json') as f:
data = json.load(f)
for item in data['tokenId']:
item['tokenId'] = item['tokenId'].replace([int('+1')])
with open('new_data.json', 'w') as f:
json.dump(data, f)
TypeError: list indices must be integers or slices, not str
Thank you!
2
Answers
The below seems to work
output
To increase the values of the "tokenId" field in your JSON file by 1, you can modify your code as follows:
In your original code, you were trying to access data[‘tokenId’] as if it was a list, but it is actually a dictionary. Instead, you need to iterate over the list data and update the "tokenId" field of each item. By using item[‘tokenId’] += 1, you increment the value of "tokenId" by 1.
Finally, the modified data is saved to a new JSON file named "new_data.json" using json.dump(data, f).
After running this code, the "new_data.json" file will contain the updated "tokenId" values with an increment of 1.