Home > Back-end >  python json how to write data one under the other instead of side by side
python json how to write data one under the other instead of side by side

Time:02-13

        self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

        with open('data.json', 'a ') as f:
            f.seek(0)
            json.dump(str(user_id), f, indent = 4 )

here, it writes user ID that created channel.

Output :

"332115091338297344""323516141777715202"

it writes the ID of more than one user, but how can I make it type from one under the other instead of side by side

CodePudding user response:

As quamrana say, json is a specific format where you can't just add a simple string.

A good way to store id in json format shoul be to create an array of id in your json like that :

{
    "ids": [
        1,
        2,
        3
    ]
}

To do that init your json file with the id's array empty. Then in python, get the array, append new id and rewrites all the file.

new_id = 444
with open('data.json', 'r ') as f:
    # read json datas
    json_datas = json.load(f)
    # get ids array
    ids = json_datas["ids"]
    # add new id    
    ids.append(new_id)
    # rebuild our json
    json_new_datas = json.dumps({"id":ids})
    f.seek(0)
    # write json into file
    f.write(json_new_datas)
  • Related