Prajakta Dumbre Prajakta Dumbre - 2 months ago 16
JSON Question

append JSON values but not get well format python

this is my code:
import json
from pprint import pprint

with open('unAnsQuestions.json') as data_file:
data = json.load(data_file)
print(len(data))
json_len = len(data)
json_len+=1
with open('unAnsQuestions.json', "a") as json_file:
json.dump({'id':json_len,'fileName':'yogesh'},json_file,indent=2)
#json_file.write("{}\n".format(json.dumps(json_len)))


[{
"id":1,
"text":"hey?",
"answer":"hi"
},
{
"id":2,
"text":"bye.?",
"answer":"see you"
}]



  • this is my code which append two values in json file.first is id and
    another is filename. and next is the json structure in which I want
    append data
    - I want append value in json file.
    - so I have Question.json which contain some data:

    but when I am going to append some value I get this output
    which is not on proper format.I want this value in bracket '[]'.

    [{
    "id":1,
    "text":"hey?",
    "answer":"hi"
    },
    {
    "id":2,
    "text":"bye.?",
    "answer":"see you"
    }]
    {
    "id": 3,
    "text":"bye.?",
    "answer":"see you"
    }

    so, the "]" is not well formatted. I tried many times but I didn't get output.can you please tell me the exact way?


Answer

The data is stored as an array of objects in file. The data needs to be appended in the array before dumping. After appending, you need to rewrite the file i.e dump the data variable.

import json from pprint 
import pprint
with open('unAnsQuestions.json') as data_file: 
  data = json.load(data_file)
  print(len(data))
  json_len = len(data)
  json_len+=1 
  with open('unAnsQuestions.json', "w") as json_file: //  write the file not append to it
    data.append({'id':json_len,'fileName':'yogesh'}) // add data in array at last index
    json.dump(data,json_file,inde‌​nt=2) // dump the array
    #json_file.write("{}\n".format(json.dumps(json_len)))
Comments