0

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

tonio94
  • 460
  • 1
  • 6
  • 18
  • Possible duplicate of [Python "extend" for a dictionary](https://stackoverflow.com/questions/577234/python-extend-for-a-dictionary) –  Aug 08 '19 at 10:32

1 Answers1

1
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 
  • Thanks for your help but In your example, if I'm not wrong, you are not adding new values in the same block. On my side, I have some entries in static, that will be written at the beginning of the code, then in a loop I have to add new key/value, just after the first ones, in the same block. And these values are dynamic, provided by SQL requests. – tonio94 Aug 08 '19 at 13:27
  • @rathodparmeshwar I've meant to explain it **in your answer**... You can edit it anytime! – FZs Aug 08 '19 at 13:39