I'm trying to append key/value in JSON by calling a function but I don't know how to do it.
This is my code :
def write_json (key, value):
# How to append key/value to json here?
with open('data.txt', 'a') as outfile:
json.dump(d, outfile)
if __name__ == '__main__':
try:
date_object = datetime.datetime.now().strftime('%Y-%m-%d')
d = {}
d['test'] = []
d['test'].append({
'dateofextract' : date_object,
})
with open('data.txt', 'a') as outfile:
json.dump(d, outfile)
# HERE there will be a SQL request that will return a Key and Value then I call write_json def to write into my json file
write_json(key, value)
I'd like to have a simple JSON file like this :
{
"test": [
{
"dateofextract": "2019-08-08"
"key1":value1,
"key2":value2
}
]
}
Or even without test block, if I only have this : { "key1":value1, "key2":value2 } it's fine too.
Thanks
EDIT
With your example code I got a Json like that :
{
"test": [
{
"dateofextract": "2019-08-08"
},
{
"key1": "value1"
}
]
}
That is not exactly what I'd like :(