tonio94
tonio94

Reputation: 510

Python function that appends datas into json

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 :(

Upvotes: 0

Views: 72

Answers (1)

rathodparmeshwar
rathodparmeshwar

Reputation: 11

import json 
vaules = []
vaules.append('value1')
vaules.append('value2')
data = {
    'test' : [

    ],
    'key2' : vaules[1]
}
a = dict()
a.update([ ('where', 4) , ('who', 5) , ('why', 6) , ('before' , 20)] )
data['test'].append(a)

jsonData = json.dumps(data)

with open('output.txt', 'w') as file:
    file.write(str(data))

#this should help 

Upvotes: 1

Related Questions