Reputation: 39
I'm working on a project IN PYTHON where I need to read and write from and to a JSON file.
The JSON file's contents look like this:
{
"buildings": [
{
"name": "Trump Towers",
"nr": "1",
"worth": "399"
},
{
"name": "Penning Towers",
"nr": "2",
"worth": "299"
}
],
"staff": [
{
"name": "D Trump",
"nr": "1",
"worth": "399"
},
{
"name": "Mr Henry",
"nr": "2",
"worth": "299"
}
]
}
Again, I need to be able to read, add and delete the individual buildings' and staff members' data
(THE FOLLOWING IS NOT IN CORRECT SYNTAX, BUT THAT'S WHY I'M ASKING, I NEED HELP WITH THIS)
(syntax not accurate) eg.
>>> read name of building nr 1
Trump Towers
>>> delete 'Trump Towers' from buildings (output to the file)
{
"buildings": [
{
"name": "Penning Towers",
"nr": "2",
"worth": "299"
}
],
"staff": [
{
"name": "D Trump",
"nr": "1",
"worth": "399"
},
{
"name": "Mr Henry",
"nr": "2",
"worth": "299"
}
]
}
>>> set 'Penning Towers' from buildings nr to 1
{
"buildings": [
{
"name": "Penning Towers",
"nr": "1",
"worth": "299"
}
],
"staff": [
{
"name": "D Trump",
"nr": "1",
"worth": "399"
},
{
"name": "Mr Henry",
"nr": "2",
"worth": "299"
}
]
}
>>> add 'Jake' with nr '3' and worth '999' to staff
{
"buildings": [
{
"name": "Penning Towers",
"nr": "1",
"worth": "299"
}
],
"staff": [
{
"name": "D Trump",
"nr": "1",
"worth": "399"
},
{
"name": "Jake",
"nr": "2",
"worth": "299"
},
{
"name": "Mr Henry",
"nr": "3",
"worth": "999"
}
]
}
Upvotes: 0
Views: 107
Reputation: 719
You can use the json
module to load the file with json.load()
in to a Python Dictionary:
import json
f = open('file.json', 'r')
d = json.load(f)
Once it's a python dict
, you can modify it as you like.
You can then write the the json to a file with json.dump(d, open('file.out', 'w'))
Upvotes: 2
Reputation: 3612
You can use json library to load json from your file as python dict and then modify that json and save it back as file.
import json
# Open json file and load its content as python dict
file = open('data.json', 'r')
my_json = json.loads(file.read())
file.close()
# Do stuff with that json
del my_json['buildings'][0]
my_json['buildings'][0]['Penning Towers'] = 1
my_json['staff'].append({'name': 'Jake', 'nr': '3', 'worth': '299'})
# Override json file with modified json
file = open('data.json', 'w')
file.write(json.dumps(my_json, indent=4))
file.close()
data.json after running our code:
{
"staff": [
{
"nr": "1",
"worth": "399",
"name": "D Trump"
},
{
"nr": "2",
"worth": "299",
"name": "Mr Henry"
},
{
"nr": "3",
"worth": "299",
"name": "Jake"
}
],
"buildings": [
{
"nr": "1",
"worth": "299",
"name": "Penning Towers"
}
]
}
Upvotes: 2