input JSON file format.
{
"Orange_2001": {
"dir": "/home/fruits/orange.check",
"path": "/home/fruits/orange",
"name": "Orange"
},
"Apple_345": {
"dir": "/home/fruits/apple.check",
"path": "/home/fruits/apple",
"name": "Apple"
}
}
Im trying to convert it to below format, but facing TypeError: string indices must be integers
{
"Orange": { "/home/fruits/orange.check": "/home/fruits/orange" },
"Apple": { "/home/fruits/apple.check": "/home/fruits/apple" }
}
Code snippet :
fruits = {}
with open('fruits.json', 'r') as data:
metadata = json.load(data)
for key, value in metadata.items():
fruits[metadata[key]['name']] = {}
fruits[metadata[key]['name']] = metadata[key]['name']['dir']
fruits[metadata[key]['name']] = metadata[key]['name']['path']
Am I missing something silly ?
CodePudding user response:
You made a typo:
metadata[key]['name']['dir']
Should be:
metadata[key]['dir']
(and the same for the line below)
Also you can replace metadata[key]
with value
everywhere, that's the point of iterating with .items() !
Additionally, your code wouldn't produce the desired output right now, as you would get : {"Orange" : "home/fruits/orange", "Apple" : "home/fruits/apple"}
. You should replace the three lines in your for loop by:
fruits[value['name']] = {value['dir']: value['path']}