Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write each JSON objects in a newline of JSON file? (Python)

Tags:

python

json

I am stuck with a problem, indeed I have a JSON file in which each objects is in a line. So, if there are 100 objects, there will be 100 lines.

[{ "attribute1" : "no1", "attribute1": "no2"}
{ "attribute1" : "no12", "attribute1": "no22"}]

I open this JSON file, and delete some atttributes of every elements.

Then, I want to write the objects back into the file in the same way (1 object = 1 line).

I have tried to do so with "indent" and "separators" but it does not work.

I would like to have :

[{ "attribute1": "no2"}
{"attribute1": "no22"}]

Thanks for reading.

    with open('verbes_lowercase.json','r+',encoding='utf-8-sig') as json_data:
        data=json.load(json_data)
        for k in range(len(data)):
            del data[k]["attribute1"]
        json.dump(data,json_data,ensure_ascii=False , indent='1', separators=(',',':'))
        json_data.seek(0)
        json_data.truncate()
like image 491
huseyin39 Avatar asked Oct 16 '22 17:10

huseyin39


1 Answers

I use a trick to do what I want, to rewrite all the objects into a new line. I write what I want to keep into a newfile.

with open('verbes_lowercase.json','r',encoding='utf-8-sig') as json_data:
    data=json.load(json_data)
    with open("verbes.json",'w',encoding="utf-8-sig") as file:
        file.write("[")
        length=len(data)
        for k in range(0,length):
            del data[k]["attribute1"]
            if (k!=length-1):
                 file.write(json.dumps(data[k], ensure_ascii=False)+",\n")
            else:
                file.write(json.dumps(data[length-1], ensure_ascii=False)+"]")
like image 102
huseyin39 Avatar answered Oct 21 '22 02:10

huseyin39