7

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()
4
  • What kind of errors do you get, because if you have a file like you described above you don't have valid json. It should have [{},{}] as notation, then you have a valid json file to load. Commented Jun 4, 2018 at 9:14
  • Sorry, it was just an example. I don't have any error. The result doesn't match my expectations. Maybe I've found , in the separators I'll put '\n'. I'll try. Commented Jun 4, 2018 at 9:17
  • \n is indeed for line breaks. If you use windows you should use \r\n, Unix systems usually only need \n Commented Jun 4, 2018 at 9:23
  • @RonNabuurs I use Windows, for text file I write \r\n for a newline but for JSON file \n seems enough . (Opened with notepad++). Commented Jun 4, 2018 at 12:48

1 Answer 1

5

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)+"]")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.